diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000000..165549e78b --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,1936 @@ +require: + - rubocop-performance + +AllCops: + # Prevent RuboCop from exploding when it finds an older-than-2.4 .ruby-version + TargetRubyVersion: 2.5 + Exclude: [] + +Bundler/DuplicatedGem: + Enabled: true + Include: + - '**/*.gemfile' + - '**/Gemfile' + - '**/gems.rb' + - '**/*.gemspec' + +Bundler/GemComment: + Enabled: false + +Bundler/GemFilename: + Enabled: false + +Bundler/GemVersion: + Enabled: false + +Bundler/InsecureProtocolSource: + Enabled: true + Include: + - '**/*.gemfile' + - '**/Gemfile' + - '**/gems.rb' + +Bundler/OrderedGems: + Enabled: false + +Gemspec/DateAssignment: + Enabled: true + +Gemspec/DuplicatedAssignment: + Enabled: true + Include: + - '**/*.gemspec' + +Gemspec/OrderedDependencies: + Enabled: false + +Gemspec/RequiredRubyVersion: + Enabled: false + +Gemspec/RubyVersionGlobalsUsage: + Enabled: false + +Layout/AccessModifierIndentation: + Enabled: true + EnforcedStyle: indent + IndentationWidth: ~ + +Layout/ArgumentAlignment: + Enabled: true + EnforcedStyle: with_fixed_indentation + +Layout/ArrayAlignment: + Enabled: true + EnforcedStyle: with_fixed_indentation + +Layout/AssignmentIndentation: + Enabled: true + IndentationWidth: ~ + +Layout/BeginEndAlignment: + Enabled: true + EnforcedStyleAlignWith: start_of_line + AutoCorrect: true + Severity: warning + +Layout/BlockAlignment: + Enabled: true + EnforcedStyleAlignWith: either + +Layout/BlockEndNewline: + Enabled: true + +Layout/CaseIndentation: + # Disabled because IndentOneStep can't be configured for one-liner cases. See: + # https://github.com/rubocop-hq/rubocop/issues/6447 + Enabled: false + +Layout/ClassStructure: + Enabled: false + +Layout/ClosingHeredocIndentation: + Enabled: true + +Layout/ClosingParenthesisIndentation: + Enabled: true + +Layout/CommentIndentation: + Enabled: true + +# Disabling for now +Layout/ConditionPosition: + Enabled: false + +Layout/DefEndAlignment: + Enabled: true + EnforcedStyleAlignWith: start_of_line + AutoCorrect: true + Severity: warning + +Layout/DotPosition: + Enabled: true + EnforcedStyle: leading + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyComment: + Enabled: true + AllowBorderComment: true + AllowMarginComment: true + +Layout/EmptyLineAfterGuardClause: + Enabled: false + +# Disabling for now +Layout/EmptyLineAfterMagicComment: + Enabled: false + +Layout/EmptyLineAfterMultilineCondition: + Enabled: false + +# Disabling for now +Layout/EmptyLineBetweenDefs: + Enabled: false + # AllowAdjacentOneLineDefs: false + # NumberOfEmptyLines: 1 + +Layout/EmptyLines: + Enabled: true + +Layout/EmptyLinesAroundAccessModifier: + Enabled: true + +Layout/EmptyLinesAroundArguments: + Enabled: true + +Layout/EmptyLinesAroundAttributeAccessor: + Enabled: false + +Layout/EmptyLinesAroundBeginBody: + Enabled: true + +Layout/EmptyLinesAroundBlockBody: + Enabled: true + EnforcedStyle: no_empty_lines + +Layout/EmptyLinesAroundClassBody: + Enabled: true + EnforcedStyle: no_empty_lines + +Layout/EmptyLinesAroundExceptionHandlingKeywords: + Enabled: true + +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +Layout/EmptyLinesAroundModuleBody: + Enabled: true + EnforcedStyle: no_empty_lines + +Layout/EndAlignment: + Enabled: true + AutoCorrect: true + EnforcedStyleAlignWith: variable + Severity: warning + +Layout/EndOfLine: + Enabled: true + EnforcedStyle: native + +Layout/ExtraSpacing: + Enabled: true + AllowForAlignment: false + AllowBeforeTrailingComments: false + ForceEqualSignAlignment: false + +Layout/FirstArgumentIndentation: + Enabled: true + EnforcedStyle: consistent + IndentationWidth: ~ + +Layout/FirstArrayElementIndentation: + Enabled: true + EnforcedStyle: consistent + IndentationWidth: ~ + +Layout/FirstArrayElementLineBreak: + Enabled: false + +Layout/FirstHashElementIndentation: + Enabled: true + EnforcedStyle: consistent + IndentationWidth: ~ + +Layout/FirstHashElementLineBreak: + Enabled: false + +Layout/FirstMethodArgumentLineBreak: + Enabled: false + +Layout/FirstMethodParameterLineBreak: + Enabled: false + +Layout/FirstParameterIndentation: + Enabled: false + +Layout/HashAlignment: + Enabled: true + EnforcedHashRocketStyle: key + EnforcedColonStyle: key + EnforcedLastArgumentHashStyle: always_inspect + +Layout/HeredocArgumentClosingParenthesis: + Enabled: false + +# Disabling for now +Layout/HeredocIndentation: + Enabled: false + +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: normal + +Layout/IndentationStyle: + Enabled: true + IndentationWidth: ~ + +Layout/IndentationWidth: + Enabled: true + Width: 2 + IgnoredPatterns: [] + +Layout/InitialIndentation: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/LeadingEmptyLines: + Enabled: true + +Layout/LineEndStringConcatenationIndentation: + Enabled: false + +Layout/LineLength: + Enabled: false + +Layout/MultilineArrayBraceLayout: + Enabled: true + EnforcedStyle: symmetrical + +Layout/MultilineArrayLineBreaks: + Enabled: false + +Layout/MultilineAssignmentLayout: + Enabled: false + +Layout/MultilineBlockLayout: + Enabled: true + +Layout/MultilineHashBraceLayout: + Enabled: true + EnforcedStyle: symmetrical + +Layout/MultilineHashKeyLineBreaks: + Enabled: false + +Layout/MultilineMethodArgumentLineBreaks: + Enabled: false + +Layout/MultilineMethodCallBraceLayout: + Enabled: true + EnforcedStyle: symmetrical + +Layout/MultilineMethodCallIndentation: + Enabled: true + EnforcedStyle: indented + IndentationWidth: ~ + +Layout/MultilineMethodDefinitionBraceLayout: + Enabled: true + EnforcedStyle: symmetrical + +Layout/MultilineOperationIndentation: + Enabled: true + EnforcedStyle: indented + IndentationWidth: ~ + +Layout/ParameterAlignment: + Enabled: true + EnforcedStyle: with_fixed_indentation + IndentationWidth: ~ + +Layout/RedundantLineBreak: + Enabled: false + +Layout/RescueEnsureAlignment: + Enabled: true + +Layout/SingleLineBlockChain: + Enabled: false + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAfterMethodName: + Enabled: true + +Layout/SpaceAfterNot: + Enabled: true + +Layout/SpaceAfterSemicolon: + Enabled: true + +Layout/SpaceAroundBlockParameters: + Enabled: true + EnforcedStyleInsidePipes: no_space + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + EnforcedStyle: space + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundMethodCallOperator: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + AllowForAlignment: true + +Layout/SpaceBeforeBlockBraces: + Enabled: true + EnforcedStyle: space + EnforcedStyleForEmptyBraces: space + +Layout/SpaceBeforeBrackets: + Enabled: false + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeComment: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + AllowForAlignment: true + +Layout/SpaceBeforeSemicolon: + Enabled: true + +# Disabling for now +Layout/SpaceInLambdaLiteral: + Enabled: false + # EnforcedStyle: require_no_space + +Layout/SpaceInsideArrayLiteralBrackets: + Enabled: true + EnforcedStyle: no_space + EnforcedStyleForEmptyBrackets: no_space + +Layout/SpaceInsideArrayPercentLiteral: + Enabled: true + +Layout/SpaceInsideBlockBraces: + Enabled: true + EnforcedStyle: space + EnforcedStyleForEmptyBraces: no_space + SpaceBeforeBlockParameters: true + +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + EnforcedStyle: no_space + EnforcedStyleForEmptyBraces: no_space + +Layout/SpaceInsideParens: + Enabled: true + EnforcedStyle: no_space + +# Disabling for now +Layout/SpaceInsidePercentLiteralDelimiters: + Enabled: false + +Layout/SpaceInsideRangeLiteral: + Enabled: true + +Layout/SpaceInsideReferenceBrackets: + Enabled: true + EnforcedStyle: no_space + EnforcedStyleForEmptyBrackets: no_space + +Layout/SpaceInsideStringInterpolation: + Enabled: true + EnforcedStyle: no_space + +Layout/TrailingEmptyLines: + Enabled: true + EnforcedStyle: final_newline + +Layout/TrailingWhitespace: + Enabled: true + AllowInHeredoc: true + +Lint/AmbiguousAssignment: + Enabled: true + +Lint/AmbiguousBlockAssociation: + Enabled: false + +# Disabling for now +Lint/AmbiguousOperator: + Enabled: false + +Lint/AmbiguousOperatorPrecedence: + Enabled: false + +Lint/AmbiguousRange: + Enabled: false + +# Disabling for now +Lint/AmbiguousRegexpLiteral: + Enabled: false + +# Disabling for now +Lint/AssignmentInCondition: + Enabled: false + # AllowSafeAssignment: true + +Lint/BigDecimalNew: + Enabled: true + +# Disabling for now +Lint/BinaryOperatorWithIdenticalOperands: + Enabled: false + +# Disabling for now +Lint/BooleanSymbol: + Enabled: false + +Lint/CircularArgumentReference: + Enabled: true + +# Disabling for now +Lint/ConstantDefinitionInBlock: + Enabled: false + +Lint/ConstantResolution: + Enabled: false + +Lint/Debugger: + Enabled: true + +# Disabling for now +Lint/DeprecatedClassMethods: + Enabled: false + +Lint/DeprecatedConstants: + Enabled: true + +Lint/DeprecatedOpenSSLConstant: + Enabled: true + +Lint/DisjunctiveAssignmentInConstructor: + Enabled: false + +Lint/DuplicateBranch: + Enabled: false + +# Disabling for now +Lint/DuplicateCaseCondition: + Enabled: false + +Lint/DuplicateElsifCondition: + Enabled: true + +Lint/DuplicateHashKey: + Enabled: true + +# Disabling for now +Lint/DuplicateMethods: + Enabled: false + +Lint/DuplicateRegexpCharacterClassElement: + Enabled: true + +Lint/DuplicateRequire: + Enabled: true + +Lint/DuplicateRescueException: + Enabled: true + +Lint/EachWithObjectArgument: + Enabled: true + +Lint/ElseLayout: + Enabled: true + +Lint/EmptyBlock: + Enabled: false + +Lint/EmptyClass: + Enabled: false + +Lint/EmptyConditionalBody: + Enabled: false + +# Disabling for now +Lint/EmptyEnsure: + Enabled: false + # AutoCorrect: true + +Lint/EmptyExpression: + Enabled: true + +Lint/EmptyFile: + Enabled: false + +Lint/EmptyInPattern: + Enabled: false + +Lint/EmptyInterpolation: + Enabled: true + +Lint/EmptyWhen: + Enabled: true + AllowComments: true + +# Disabling for now +Lint/EnsureReturn: + Enabled: false + +Lint/ErbNewArguments: + Enabled: true + +Lint/FlipFlop: + Enabled: true + +# Disabling for now +Lint/FloatComparison: + Enabled: false + +Lint/FloatOutOfRange: + Enabled: true + +Lint/FormatParameterMismatch: + Enabled: true + +Lint/HashCompareByIdentity: + Enabled: false + +Lint/HeredocMethodCallPosition: + Enabled: false + +Lint/IdentityComparison: + Enabled: true + +Lint/ImplicitStringConcatenation: + Enabled: true + +# Disabling for now +Lint/IneffectiveAccessModifier: + Enabled: false + +# Disabling for now +Lint/InheritException: + Enabled: false + # EnforcedStyle: runtime_error + +# Disabling for now +Lint/InterpolationCheck: + Enabled: false + +Lint/LambdaWithoutLiteralBlock: + Enabled: false + +Lint/LiteralAsCondition: + Enabled: true + +Lint/LiteralInInterpolation: + Enabled: true + +Lint/Loop: + Enabled: true + +Lint/MissingCopEnableDirective: + Enabled: true + MaximumRangeSize: .inf + +Lint/MissingSuper: + Enabled: false + +Lint/MixedRegexpCaptureTypes: + Enabled: true + +Lint/MultipleComparison: + Enabled: true + +# Disabling for now +Lint/NestedMethodDefinition: + Enabled: false + +Lint/NestedPercentLiteral: + Enabled: true + +Lint/NextWithoutAccumulator: + Enabled: true + +Lint/NoReturnInBeginEndBlocks: + Enabled: false + +# Disabling for now +Lint/NonDeterministicRequireOrder: + Enabled: false + +# Disabling for now +Lint/NonLocalExitFromIterator: + Enabled: false + +Lint/NumberConversion: + Enabled: false + +Lint/NumberedParameterAssignment: + Enabled: true + +Lint/OrAssignmentToConstant: + Enabled: true + +Lint/OrderedMagicComments: + Enabled: true + +Lint/OutOfRangeRegexpRef: + Enabled: true + +# Disabling for now +Lint/ParenthesesAsGroupedExpression: + Enabled: false + +Lint/PercentStringArray: + Enabled: false + +Lint/PercentSymbolArray: + Enabled: true + +# Disabling for now +Lint/RaiseException: + Enabled: false + +Lint/RandOne: + Enabled: true + +Lint/RedundantCopDisableDirective: + Enabled: true + +Lint/RedundantCopEnableDirective: + Enabled: false + +Lint/RedundantDirGlobSort: + Enabled: false + +# Disabling for now +Lint/RedundantRequireStatement: + Enabled: false + +Lint/RedundantSafeNavigation: + Enabled: false + +# Disabling for now +Lint/RedundantSplatExpansion: + Enabled: false + +# Disabling for now +Lint/RedundantStringCoercion: + Enabled: false + +Lint/RedundantWithIndex: + Enabled: true + +Lint/RedundantWithObject: + Enabled: true + +Lint/RegexpAsCondition: + Enabled: true + +Lint/RequireParentheses: + Enabled: true + +# Disabling for now +Lint/RescueException: + Enabled: false + +Lint/RescueType: + Enabled: true + +Lint/ReturnInVoidContext: + Enabled: true + +Lint/SafeNavigationChain: + Enabled: true + AllowedMethods: + - present? + - blank? + - presence + - try + - try! + +Lint/SafeNavigationConsistency: + Enabled: true + AllowedMethods: + - present? + - blank? + - presence + - try + - try! + +Lint/SafeNavigationWithEmpty: + Enabled: true + +Lint/ScriptPermission: + Enabled: false + +Lint/SelfAssignment: + Enabled: true + +Lint/SendWithMixinArgument: + Enabled: false + +# Disabling for now +Lint/ShadowedArgument: + Enabled: false + # IgnoreImplicitReferences: false + +# Disabling for now +Lint/ShadowedException: + Enabled: false + +Lint/ShadowingOuterLocalVariable: + Enabled: false + +Lint/StructNewOverride: + Enabled: false + +Lint/SuppressedException: + Enabled: false + +# Disabling for now +Lint/SymbolConversion: + Enabled: false + +Lint/Syntax: + Enabled: true + +Lint/ToEnumArguments: + Enabled: false + +Lint/ToJSON: + Enabled: false + +Lint/TopLevelReturnWithArgument: + Enabled: true + +Lint/TrailingCommaInAttributeDeclaration: + Enabled: true + +Lint/TripleQuotes: + Enabled: true + +# Disabling for now +Lint/UnderscorePrefixedVariableName: + Enabled: false + +Lint/UnexpectedBlockArity: + Enabled: false + +# Disabling for now +Lint/UnifiedInteger: + Enabled: false + +Lint/UnmodifiedReduceAccumulator: + Enabled: false + +# Disabling for now +Lint/UnreachableCode: + Enabled: false + +Lint/UnreachableLoop: + Enabled: false + +Lint/UnusedBlockArgument: + Enabled: false + +Lint/UnusedMethodArgument: + Enabled: false + +Lint/UriEscapeUnescape: + Enabled: true + +Lint/UriRegexp: + Enabled: true + +Lint/UselessAccessModifier: + Enabled: false + +# Disabling for now +Lint/UselessAssignment: + Enabled: false + +Lint/UselessElseWithoutRescue: + Enabled: true + +Lint/UselessMethodDefinition: + Enabled: false + +Lint/UselessSetterCall: + Enabled: true + +# Disabling for now +Lint/UselessTimes: + Enabled: false + +# Disabling for now +Lint/Void: + Enabled: false + # CheckForMethodsWithNoSideEffects: false + +Lint/IncompatibleIoSelectWithFiberScheduler: + Enabled: false + +Lint/RequireRelativeSelfPath: + Enabled: true + +Metrics/AbcSize: + Enabled: false + +Metrics/BlockLength: + Enabled: false + +Metrics/BlockNesting: + Enabled: false + +Metrics/ClassLength: + Enabled: false + +Metrics/CyclomaticComplexity: + Enabled: false + +Metrics/MethodLength: + Enabled: false + +Metrics/ModuleLength: + Enabled: false + +Metrics/ParameterLists: + Enabled: false + +Metrics/PerceivedComplexity: + Enabled: false + +Migration/DepartmentName: + Enabled: true + +Naming/AccessorMethodName: + Enabled: false + +Naming/AsciiIdentifiers: + Enabled: false + +# Disabling for now +Naming/BinaryOperatorParameterName: + Enabled: false + +Naming/BlockParameterName: + Enabled: true + MinNameLength: 1 + AllowNamesEndingInNumbers: true + AllowedNames: [] + ForbiddenNames: [] + +Naming/ClassAndModuleCamelCase: + Enabled: true + +Naming/ConstantName: + Enabled: true + +Naming/FileName: + Enabled: false + +Naming/HeredocDelimiterCase: + Enabled: true + EnforcedStyle: uppercase + +Naming/HeredocDelimiterNaming: + Enabled: false + +Naming/InclusiveLanguage: + Enabled: false + +Naming/MemoizedInstanceVariableName: + Enabled: false + +Naming/MethodName: + Enabled: false + +Naming/MethodParameterName: + Enabled: false + +Naming/PredicateName: + Enabled: false + +Naming/RescuedExceptionsVariableName: + Enabled: false + +Naming/VariableName: + Enabled: false + # EnforcedStyle: snake_case + +Naming/VariableNumber: + Enabled: false + +Performance/AncestorsInclude: + Enabled: false + +Performance/ArraySemiInfiniteRangeSlice: + Enabled: false + +Performance/BigDecimalWithNumericArgument: + Enabled: true + +Performance/BindCall: + Enabled: true + +# Disabling for now +Performance/BlockGivenWithExplicitBlock: + Enabled: false + +# Disabling for now +Performance/Caller: + Enabled: false + +Performance/CaseWhenSplat: + Enabled: false + +Performance/Casecmp: + Enabled: false + +Performance/ChainArrayAllocation: + Enabled: false + +Performance/CollectionLiteralInLoop: + Enabled: false + +Performance/CompareWithBlock: + Enabled: true + +# Disabling for now +Performance/ConstantRegexp: + Enabled: false + +# Disabling for now +Performance/Count: + Enabled: false + +Performance/DeletePrefix: + Enabled: false + +Performance/DeleteSuffix: + Enabled: false + +# Disabling for now +Performance/Detect: + Enabled: false + +# Disabling for now +Performance/DoubleStartEndWith: + Enabled: false + # IncludeActiveSupportAliases: false + +Performance/EndWith: + Enabled: true + +Performance/FixedSize: + Enabled: true + +Performance/FlatMap: + Enabled: true + EnabledForFlattenWithoutParams: false + +# Disabling for now +Performance/InefficientHashSearch: + Enabled: false + # Safe: false + +Performance/IoReadlines: + Enabled: false + +Performance/MapCompact: + Enabled: false + +Performance/MethodObjectAsBlock: + Enabled: false + +Performance/OpenStruct: + Enabled: false + +Performance/RangeInclude: + Enabled: true + Safe: false + +Performance/RedundantBlockCall: + Enabled: false + +Performance/RedundantEqualityComparisonBlock: + Enabled: false + +# Disabling for now +Performance/RedundantMatch: + Enabled: false + +# Disabling for now +Performance/RedundantMerge: + Enabled: false + # MaxKeyValuePairs: 2 + +Performance/RedundantSortBlock: + Enabled: true + +Performance/RedundantSplitRegexpArgument: + Enabled: true + +Performance/RedundantStringChars: + Enabled: true + +# Disabling for now +Performance/RegexpMatch: + Enabled: false + +# Disabling for now +Performance/ReverseEach: + Enabled: false + +Performance/ReverseFirst: + Enabled: true + +Performance/SelectMap: + Enabled: false + +Performance/Size: + Enabled: true + +Performance/SortReverse: + Enabled: true + +Performance/Squeeze: + Enabled: true + +# Disabling for now +Performance/StartWith: + Enabled: false + +Performance/StringInclude: + Enabled: false + +# Disabling for now +Performance/StringReplacement: + Enabled: false + +Performance/Sum: + Enabled: false + +Performance/TimesMap: + Enabled: false + +# Disabling for now +Performance/UnfreezeString: + Enabled: false + +Performance/UriDefaultParser: + Enabled: true + +# Disabling for now +Security/Eval: + Enabled: false + +# Disabling for now +Security/JSONLoad: + Enabled: false + # AutoCorrect: false + # SafeAutoCorrect: false + +Security/MarshalLoad: + Enabled: false + +Security/Open: + Enabled: true + Safe: false + +# Disabling for now +Security/YAMLLoad: + Enabled: false + # SafeAutoCorrect: false + +Security/IoMethods: + Enabled: false + Safe: false + +# raised unrecognized cop or department +# Standard/BlockSingleLineBraces: +# Enabled: true + +Style/AccessModifierDeclarations: + Enabled: false + +Style/AccessorGrouping: + Enabled: false + +# Disabling for now +Style/Alias: + Enabled: false + # EnforcedStyle: prefer_alias_method + +# Disabling for now +Style/AndOr: + Enabled: false + +Style/ArgumentsForwarding: + Enabled: true + AllowOnlyRestArgument: true + +Style/ArrayCoercion: + Enabled: false + +Style/ArrayJoin: + Enabled: true + +Style/AsciiComments: + Enabled: false + +Style/Attr: + Enabled: true + +Style/AutoResourceCleanup: + Enabled: false + +# Disabling for now +Style/BarePercentLiterals: + Enabled: false + EnforcedStyle: bare_percent + +Style/BeginBlock: + Enabled: true + +Style/BisectedAttrAccessor: + Enabled: false + +Style/BlockComments: + Enabled: true + +Style/BlockDelimiters: + Enabled: false + +Style/CaseEquality: + Enabled: false + +Style/CaseLikeIf: + Enabled: false + +Style/CharacterLiteral: + Enabled: true + +Style/ClassAndModuleChildren: + Enabled: false + +# Disabling for now +Style/ClassCheck: + Enabled: false + # EnforcedStyle: is_a? + +# Disabling for now +Style/ClassEqualityComparison: + Enabled: false + +Style/ClassMethods: + Enabled: true + +Style/ClassMethodsDefinitions: + Enabled: false + +Style/ClassVars: + Enabled: false + +Style/CollectionCompact: + Enabled: false + +Style/CollectionMethods: + Enabled: false + +# Disabling for now +Style/ColonMethodCall: + Enabled: false + +Style/ColonMethodDefinition: + Enabled: true + +Style/CombinableLoops: + Enabled: false + +# Disabling for now +Style/CommandLiteral: + Enabled: false + # EnforcedStyle: mixed + # AllowInnerBackticks: false + +Style/CommentAnnotation: + Enabled: false + +Style/CommentedKeyword: + Enabled: false + +# Disabling for now +Style/ConditionalAssignment: + Enabled: false + # EnforcedStyle: assign_to_condition + # SingleLineConditionsOnly: true + # IncludeTernaryExpressions: true + +Style/ConstantVisibility: + Enabled: false + +Style/Copyright: + Enabled: false + +Style/DateTime: + Enabled: false + +Style/DefWithParentheses: + Enabled: true + +# Disabling for now +Style/Dir: + Enabled: false + +Style/DisableCopsWithinSourceCodeDirective: + Enabled: false + +Style/DocumentDynamicEvalDefinition: + Enabled: false + +Style/Documentation: + Enabled: false + +Style/DocumentationMethod: + Enabled: false + +Style/DoubleCopDisableDirective: + Enabled: false + +Style/DoubleNegation: + Enabled: false + +Style/EachForSimpleLoop: + Enabled: true + +# Disabling for now +Style/EachWithObject: + Enabled: false + +Style/EmptyBlockParameter: + Enabled: true + +# Disabling for now +Style/EmptyCaseCondition: + Enabled: false + +Style/EmptyElse: + Enabled: true + EnforcedStyle: both + +# Disabling for now +Style/EmptyLambdaParameter: + Enabled: false + +# Disabling for now +Style/EmptyLiteral: + Enabled: false + +# Disabling for now +Style/EmptyMethod: + Enabled: false + # EnforcedStyle: expanded + +# Disabling for now +Style/Encoding: + Enabled: false + +Style/EndBlock: + Enabled: true + AutoCorrect: true + +Style/EndlessMethod: + Enabled: false + +# Disabling for now +Style/EvalWithLocation: + Enabled: false + +Style/EvenOdd: + Enabled: false + +Style/ExpandPathArguments: + Enabled: false + +Style/ExplicitBlockArgument: + Enabled: false + +Style/ExponentialNotation: + Enabled: false + +Style/FloatDivision: + Enabled: false + +# Disabling for now +Style/For: + Enabled: false + # EnforcedStyle: each + +Style/FormatString: + Enabled: false + +Style/FormatStringToken: + Enabled: false + +Style/FrozenStringLiteralComment: + Enabled: false + +# Disabling for now +Style/GlobalStdStream: + Enabled: false + +# Disabling for now +Style/GlobalVars: + Enabled: false + # AllowedVariables: [] + +Style/GuardClause: + Enabled: false + +Style/HashAsLastArrayItem: + Enabled: false + +# Disabling for now +Style/HashConversion: + Enabled: false + +Style/HashEachMethods: + Enabled: false + +Style/HashExcept: + Enabled: true + +Style/HashLikeCase: + Enabled: false + +# Documentation: https://docs.rubocop.org/rubocop/cops_style.html#stylehashsyntax +# I believe we want either hash_rockets or no_mixed_keys +# Disabling for now +Style/HashSyntax: + Enabled: false + # EnforcedStyle: ruby19_no_mixed_keys + +Style/HashTransformKeys: + Enabled: false + +Style/HashTransformValues: + Enabled: false + +# Disabling for now +Style/IdenticalConditionalBranches: + Enabled: false + +# Disabling for now +Style/IfInsideElse: + Enabled: false + +Style/IfUnlessModifier: + Enabled: false + +Style/IfUnlessModifierOfIfUnless: + Enabled: true + +Style/IfWithBooleanLiteralBranches: + Enabled: true + +Style/IfWithSemicolon: + Enabled: true + +Style/ImplicitRuntimeError: + Enabled: false + +Style/InPatternThen: + Enabled: false + +# Disabling for now +Style/InfiniteLoop: + Enabled: false + +Style/InlineComment: + Enabled: false + +Style/InverseMethods: + Enabled: false + +Style/IpAddresses: + Enabled: false + +# Disabling for now +Style/KeywordParametersOrder: + Enabled: false + +Style/Lambda: + Enabled: false + +Style/LambdaCall: + Enabled: true + EnforcedStyle: call + +# Disabling for now +Style/LineEndConcatenation: + Enabled: false + # SafeAutoCorrect: false + +Style/MethodCallWithArgsParentheses: + Enabled: false + +# Disabling for now +Style/MethodCallWithoutArgsParentheses: + Enabled: false + IgnoredMethods: [] + +Style/MethodCalledOnDoEndBlock: + Enabled: false + +Style/MethodDefParentheses: + Enabled: false + +Style/MinMax: + Enabled: false + +Style/MissingElse: + Enabled: false + +# Disabling for now +Style/MissingRespondToMissing: + Enabled: false + +# Disabling for now +Style/MixinGrouping: + Enabled: false + # EnforcedStyle: separated + +# Disabling for now +Style/MixinUsage: + Enabled: false + +Style/ModuleFunction: + Enabled: false + +Style/MultilineBlockChain: + Enabled: false + +Style/MultilineIfModifier: + Enabled: true + +Style/MultilineIfThen: + Enabled: true + +Style/MultilineInPatternThen: + Enabled: false + +# Disabling for now +Style/MultilineMemoization: + Enabled: false + # EnforcedStyle: keyword + +Style/MultilineMethodSignature: + Enabled: false + +Style/MultilineTernaryOperator: + Enabled: false + +Style/MultilineWhenThen: + Enabled: true + +Style/MultipleComparison: + Enabled: false + +Style/MutableConstant: + Enabled: false + +Style/NegatedIf: + Enabled: false + +Style/NegatedIfElseCondition: + Enabled: false + +Style/NegatedUnless: + Enabled: false + +# Disabling for now +Style/NegatedWhile: + Enabled: false + +Style/NestedModifier: + Enabled: true + +# Disabling for now +Style/NestedParenthesizedCalls: + Enabled: false + # AllowedMethods: + # - be + # - be_a + # - be_an + # - be_between + # - be_falsey + # - be_kind_of + # - be_instance_of + # - be_truthy + # - be_within + # - eq + # - eql + # - end_with + # - include + # - match + # - raise_error + # - respond_to + # - start_with + +Style/NestedTernaryOperator: + Enabled: true + +Style/Next: + Enabled: false + +# Disabling for now +Style/NilComparison: + Enabled: false + # EnforcedStyle: predicate + +# Disabling for now +Style/NilLambda: + Enabled: false + +# Disabling for now +Style/NonNilCheck: + Enabled: false + # IncludeSemanticChanges: false + +Style/Not: + Enabled: true + +# Disabling for now +Style/NumericLiteralPrefix: + Enabled: false + # EnforcedOctalStyle: zero_with_o + +Style/NumericLiterals: + Enabled: false + +Style/NumericPredicate: + Enabled: false + +Style/OneLineConditional: + Enabled: true + +Style/OptionHash: + Enabled: false + +Style/OptionalArguments: + Enabled: true + +Style/OptionalBooleanParameter: + Enabled: false + +# Disabling for now +Style/OrAssignment: + Enabled: false + +Style/ParallelAssignment: + Enabled: false + +Style/ParenthesesAroundCondition: + Enabled: true + AllowSafeAssignment: true + AllowInMultilineConditions: false + +Style/PercentLiteralDelimiters: + Enabled: true + PreferredDelimiters: + default: () + '%i': '[]' + '%I': '[]' + '%r': '{}' + '%w': '[]' + '%W': '[]' + +Style/PercentQLiterals: + Enabled: false + +Style/PerlBackrefs: + Enabled: false + +Style/PreferredHashMethods: + Enabled: false + +# Disabling for now +Style/Proc: + Enabled: false + +Style/QuotedSymbols: + Enabled: false + +Style/RaiseArgs: + Enabled: false + +Style/RandomWithOffset: + Enabled: true + +Style/RedundantArgument: + Enabled: false + +# Disabling for now +Style/RedundantAssignment: + Enabled: false + +# Disabling for now +Style/RedundantBegin: + Enabled: false + +Style/RedundantCapitalW: + Enabled: false + +Style/RedundantCondition: + Enabled: true + +Style/RedundantConditional: + Enabled: true + +Style/RedundantException: + Enabled: true + +Style/RedundantFetchBlock: + Enabled: true + +Style/RedundantFileExtensionInRequire: + Enabled: true + +# Disabling for now +Style/RedundantFreeze: + Enabled: false + +# Disabling for now +Style/RedundantInterpolation: + Enabled: false + +# Disabling for now +Style/RedundantParentheses: + Enabled: false + +# Disabling for now +Style/RedundantPercentQ: + Enabled: false + +Style/RedundantRegexpCharacterClass: + Enabled: true + +# Disabling for now +Style/RedundantRegexpEscape: + Enabled: false + +# Disabling for now +Style/RedundantReturn: + Enabled: false +# AllowMultipleReturnValues: false + +# Disabling for now +Style/RedundantSelf: + Enabled: false + +Style/RedundantSelfAssignment: + Enabled: false + +Style/RedundantSelfAssignmentBranch: + Enabled: false + +# Disabling for now +Style/RedundantSort: + Enabled: false + +Style/RedundantSortBy: + Enabled: true + +Style/RegexpLiteral: + Enabled: false + +# Disabling for now +Style/RescueModifier: + Enabled: false + +# Disabling for now +Style/RescueStandardError: + Enabled: false + # EnforcedStyle: implicit + +Style/ReturnNil: + Enabled: false + +# Can't use, not available in Ruby 2.2 +Style/SafeNavigation: + Enabled: false + # ConvertCodeThatCanStartToReturnNil: false + # AllowedMethods: + # - present? + # - blank? + # - presence + # - try + # - try! + +Style/Sample: + Enabled: true + +Style/SelfAssignment: + Enabled: true + +# Disabling for now +Style/Semicolon: + Enabled: false + # AllowAsExpressionSeparator: false + +Style/Send: + Enabled: false + +Style/SignalException: + Enabled: false + +Style/SingleArgumentDig: + Enabled: false + +Style/SingleLineBlockParams: + Enabled: false + +# Disabling for now +Style/SingleLineMethods: + Enabled: false + # AllowIfMethodIsEmpty: false + +Style/SlicingWithRange: + Enabled: true + +Style/SoleNestedConditional: + Enabled: false + +Style/SpecialGlobalVars: + Enabled: false + +Style/StabbyLambdaParentheses: + Enabled: true + EnforcedStyle: require_parentheses + +Style/StaticClass: + Enabled: false + +# Do we want this one? Use warn instead of STDERR.puts +Style/StderrPuts: + Enabled: false + +Style/StringChars: + Enabled: true + +Style/StringConcatenation: + Enabled: false + +Style/StringHashKeys: + Enabled: false + +# Disabling for now +Style/StringLiterals: + Enabled: false +# EnforcedStyle: double_quotes +# ConsistentQuotesInMultiline: false + +# Disabling for now +Style/StringLiteralsInInterpolation: + Enabled: false + # EnforcedStyle: double_quotes + +Style/StringMethods: + Enabled: false + +Style/Strip: + Enabled: true + +Style/StructInheritance: + Enabled: false + +Style/SwapValues: + Enabled: false + +Style/SymbolArray: + Enabled: false + +# Disabling for now +Style/SymbolLiteral: + Enabled: false + +Style/SymbolProc: + Enabled: false + +Style/TernaryParentheses: + Enabled: true + EnforcedStyle: require_no_parentheses + AllowSafeAssignment: true + +Style/TopLevelMethodDefinition: + Enabled: false + +Style/TrailingBodyOnClass: + Enabled: true + +Style/TrailingBodyOnMethodDefinition: + Enabled: true + +Style/TrailingBodyOnModule: + Enabled: true + +Style/TrailingCommaInArguments: + Enabled: true + EnforcedStyleForMultiline: no_comma + +Style/TrailingCommaInArrayLiteral: + Enabled: true + EnforcedStyleForMultiline: no_comma + +Style/TrailingCommaInBlockArgs: + Enabled: true + +Style/TrailingCommaInHashLiteral: + Enabled: true + EnforcedStyleForMultiline: no_comma + +Style/TrailingMethodEndStatement: + Enabled: true + +Style/TrailingUnderscoreVariable: + Enabled: false + +# Do we want? Performance test first +Style/TrivialAccessors: + Enabled: false +# ExactNameMatch: true +# AllowPredicates: true +# AllowDSLWriters: false +# IgnoreClassMethods: false +# AllowedMethods: +# - to_ary +# - to_a +# - to_c +# - to_enum +# - to_h +# - to_hash +# - to_i +# - to_int +# - to_io +# - to_open +# - to_path +# - to_proc +# - to_r +# - to_regexp +# - to_str +# - to_s +# - to_sym + +Style/UnlessElse: + Enabled: true + +Style/UnlessLogicalOperators: + Enabled: false + +# Disabling for now +Style/UnpackFirst: + Enabled: false + +# Disabling for now +Style/VariableInterpolation: + Enabled: false + +Style/WhenThen: + Enabled: true + +Style/WhileUntilDo: + Enabled: true + +Style/WhileUntilModifier: + Enabled: false + +Style/WordArray: + Enabled: false + +# Disabling for now +Style/YodaCondition: + Enabled: false + # EnforcedStyle: forbid_for_all_comparison_operators + +Style/ZeroLengthPredicate: + Enabled: false + +Style/NumberedParameters: + Enabled: false + +Style/NumberedParametersLimit: + Enabled: false + +Style/SelectByRegexp: + Enabled: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c2dd0fdc2b..20bd358c21 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,7 +66,8 @@ issues](../../issues?q=is%3Aissue+is%3Aclosed). ### Pull Requests We can only accept PRs for version v6.12.0 or greater due to open source -licensing restrictions. +licensing restrictions. Please set the merge branch to `dev` unless the issue +states otherwise. ### Code of Conduct @@ -84,18 +85,29 @@ release from this repo, use the appropriate tag. New Relic usually pushes beta versions of a release to a working branch before tagging them for General Availability. +The `main` branch houses the code from the latest release. The `dev` branch +includes unreleased work. Please create all new branches off of `dev`. + ## Development Environment Setup 1. Fork and clone the repo locally - Fork the repository inside GitHub - `git clone git@github.com:/newrelic-ruby-agent.git` 1. Pick a Ruby version - - Use rbenv or rvm to install any version of Ruby between 2.2 up to 3.0.1 + - Use rbenv or rvm to install any version of Ruby between 2.2 up to 3.1 1. Install development dependencies - `bundle install` 1. Check that your env is setup correctly - `bundle exec rake` +**Optional:** Install [lefthook](https://github.com/evilmartians/lefthook) to +integrate our team's git hooks, such as [rubocop](https://github.com/rubocop/rubocop) +linting into your workflow. + +**Note:** These setup instructions will not allow you to run the entire test +suite. Some of our suites require services such as MySQL, Postgres, Redis, and +others to run. + ## Testing The agent includes a suite of unit and functional tests which should be used to diff --git a/Guardfile b/Guardfile index ae05658963..7135468135 100644 --- a/Guardfile +++ b/Guardfile @@ -1,24 +1,24 @@ require './test/multiverse/lib/multiverse/bundler_patch' -test_folders = Dir.glob("test/new_relic/*").select{|f| File.directory?(f)} -test_folders += Dir.glob("test/new_relic/**/*").select{|f| File.directory?(f)} +test_folders = Dir.glob("test/new_relic/*").select { |f| File.directory?(f) } +test_folders += Dir.glob("test/new_relic/**/*").select { |f| File.directory?(f) } -rake_lib_path = Bundler.with_unbundled_env{ `bundle exec gem which rake`.chomp.gsub("lib/rake.rb", "lib") } -ruby_options = %{-w -I"#{rake_lib_path}" "#{rake_lib_path}/rake/rake_test_loader.rb"} +rake_lib_path = Bundler.with_unbundled_env { `bundle exec gem which rake`.chomp.gsub("lib/rake.rb", "lib") } +ruby_options = %(-w -I"#{rake_lib_path}" "#{rake_lib_path}/rake/rake_test_loader.rb") guard_options = { spring: "bundle exec ruby #{ruby_options} ", - test_folders: ['test/new_relic'] + test_folders, + test_folders: ['test/new_relic'] + test_folders, all_after_pass: false, all_on_start: false } guard :minitest, guard_options do - watch(%r{^lib/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" } + watch(%r{^lib/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" } watch(%r{^test/.+_test\.rb$}) - watch(%r{^test/rum/.*}) { "test/new_relic/rack/browser_monitoring_test.rb" } + watch(%r{^test/rum/.*}) { "test/new_relic/rack/browser_monitoring_test.rb" } watch(%r{^test/fixtures/cross_agent_tests/distributed_tracing/(.+).json}) { |m| "test/new_relic/agent/distributed_tracing/#{m[1]}_cross_agent_test.rb" } - watch('test/test_helper.rb') { "test/new_relic" } + watch('test/test_helper.rb') { "test/new_relic" } watch('test/agent_helper.rb') { "test/new_relic" } watch('lib/new_relic/agent/configuration/default_source.rb') { "test/new_relic/agent/configuration/orphan_configuration_test.rb" } watch(%r{^lib/new_relic/agent/transaction/(.+).rb}) { |m| "test/new_relic/agent/distributed_tracing/#{m[1]}_cross_agent_test.rb" } diff --git a/Rakefile b/Rakefile index 805ad8d446..802592cc76 100644 --- a/Rakefile +++ b/Rakefile @@ -10,7 +10,7 @@ task :test => ['test:newrelic'] namespace :test do desc "Run all tests" - task :all => %w{newrelic multiverse} + task :all => %w[newrelic multiverse] begin require 'test_bisect' @@ -27,14 +27,14 @@ namespace :test do require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'performance', 'lib', 'performance')) options = {} options[:suite] = args[:suite] if args[:suite] - options[:name] = args[:name] if args[:name] + options[:name] = args[:name] if args[:name] Performance::Runner.new(options).run_and_report end desc "Run agent within existing mini environments" task :env, [:env1, :env2, :env3, :env4, :env5, :env6] => [] do |t, args| require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'environments', 'lib', 'environments', 'runner')) - Environments::Runner.new(args.map{|_,v| v}).run_and_report + Environments::Runner.new(args.map { |_, v| v }).run_and_report end Rake::TestTask.new(:intentional_fail) do |t| @@ -51,11 +51,10 @@ namespace :test do # Note unit testing task is defined in lib/tasks/tests.rake to facilitate # running them in a rails application environment. - end desc 'Record build number and stage' -task :record_build, [ :build_number, :stage ] do |t, args| +task :record_build, [:build_number, :stage] do |t, args| build_string = args.build_number build_string << ".#{args.stage}" unless args.stage.nil? || args.stage.empty? @@ -111,7 +110,7 @@ end namespace :cross_agent_tests do cross_agent_tests_upstream_path = File.expand_path(File.join(File.dirname(__FILE__), '..', 'cross_agent_tests')) - cross_agent_tests_local_path = File.expand_path(File.join(File.dirname(__FILE__), 'test', 'fixtures', 'cross_agent_tests')) + cross_agent_tests_local_path = File.expand_path(File.join(File.dirname(__FILE__), 'test', 'fixtures', 'cross_agent_tests')) # Note: before you pull, make sure your local repo is on the correct, synced branch! desc 'Pull latest changes from cross_agent_tests repo' @@ -137,4 +136,3 @@ task :console do ARGV.clear Pry.start end - diff --git a/bin/mongrel_rpm b/bin/mongrel_rpm index 7b4f398d82..c56931879a 100755 --- a/bin/mongrel_rpm +++ b/bin/mongrel_rpm @@ -5,14 +5,14 @@ require 'rack/handler/mongrel' require 'optparse' port = 3000 -options = { } +options = {} appname = nil OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [options] [app_name]" - opts.on("-p", "--port=port", Integer, "default: #{port}") { | port | } - opts.on("--[no-]logging", "turn off request logging" ) { | l | options[:logging] = l } - opts.on("--license=license_key", "override license key" ) { | l | options[:license_key] = l } - opts.on("--install", "install a newrelic.yml template" ) { | l | options[:install] = true } + opts.on("-p", "--port=port", Integer, "default: #{port}") { |port| } + opts.on("--[no-]logging", "turn off request logging") { |l| options[:logging] = l } + opts.on("--license=license_key", "override license key") { |l| options[:license_key] = l } + opts.on("--install", "install a newrelic.yml template") { |l| options[:install] = true } opts.separator "" opts.separator "app_name is the name of the application where the metrics will be stored" opts.separator "" @@ -26,8 +26,7 @@ ru_file = File.expand_path(File.join(File.dirname(__FILE__), "..", "lib", "new_r rackup_code = File.read ru_file builder = Rack::Builder.new { eval rackup_code, binding, ru_file } -options = { :Host => '127.0.0.1', :Port => port } -Rack::Handler::Mongrel.run(builder.to_app, options) do | server | - NewRelic::Agent.logger.info "Started Mongrel listening for '#{NewRelic::Control.instance.app_names.join(" and ")}' data at #{server.host}:#{server.port}" +options = {:Host => '127.0.0.1', :Port => port} +Rack::Handler::Mongrel.run(builder.to_app, options) do |server| + NewRelic::Agent.logger.info "Started Mongrel listening for '#{NewRelic::Control.instance.app_names.join(" and ")}' data at #{server.host}:#{server.port}" end - diff --git a/bin/newrelic b/bin/newrelic index 1c4f24a205..0516308d57 100755 --- a/bin/newrelic +++ b/bin/newrelic @@ -2,7 +2,7 @@ # executes one of the commands in the new_relic/commands directory # pass the name of the command as an argument -$LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__), '..','lib')) +$LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')) require 'new_relic/cli/command' begin NewRelic::Cli::Command.run diff --git a/bin/nrdebug b/bin/nrdebug index c20c07ea42..8652148d27 100755 --- a/bin/nrdebug +++ b/bin/nrdebug @@ -7,7 +7,7 @@ require 'tempfile' require 'rbconfig' -def fail(msg, opts={}) +def fail(msg, opts = {}) $stderr.puts(msg) usage() if opts[:usage] exit(-1) @@ -84,7 +84,7 @@ class ProcessDataProvider def self.for_process(pid) case RbConfig::CONFIG['target_os'] - when /linux/ then LinuxProcessDataProvider.new(pid) + when /linux/ then LinuxProcessDataProvider.new(pid) when /darwin/ then DarwinProcessDataProvider.new(pid) end end @@ -170,7 +170,7 @@ end class ProcessReport attr_reader :target, :path - def initialize(target, path=nil) + def initialize(target, path = nil) @target = target @path = path end @@ -185,7 +185,7 @@ class ProcessReport end end - def section(f, name=nil) + def section(f, name = nil) content = begin yield rescue StandardError => e @@ -200,13 +200,13 @@ class ProcessReport def generate open do |f| - section(f, "Time") { Time.now } - section(f, "PID") { @target.pid } - section(f, "Command") { @target.procline } - section(f, "RSS") { @target.rss } - section(f, "CPU") { @target.cpu } - section(f, "Parent PID") { @target.ppid } - section(f, "OS") { ShellWrapper.execute('uname -a') } + section(f, "Time") { Time.now } + section(f, "PID") { @target.pid } + section(f, "Command") { @target.procline } + section(f, "RSS") { @target.rss } + section(f, "CPU") { @target.cpu } + section(f, "Parent PID") { @target.ppid } + section(f, "OS") { ShellWrapper.execute('uname -a') } section(f, "Environment") { @target.environment } section(f) do @@ -214,13 +214,13 @@ class ProcessReport if c_backtraces.match(/could not attach/i) fail("Failed to attach to target process. Please try again with sudo.") end - section(f, "C Backtraces") { c_backtraces } + section(f, "C Backtraces") { c_backtraces } section(f, "Ruby Backtrace(s)") { ruby_backtraces } end section(f, "Open files") { @target.open_files } section(f, "Log") do - commands = Logger.messages.map { |(_,msg)| msg } + commands = Logger.messages.map { |(_, msg)| msg } commands.join("\n") end end @@ -243,7 +243,7 @@ def prompt_for_confirmation(target_pid, target_cmd) puts '' puts "To continue, type 'continue':" - until ($stdin.gets.strip == 'continue') do + until $stdin.gets.strip == 'continue' puts "Please type 'continue' to continue, or ctrl-c to abort." end end diff --git a/infinite_tracing/Rakefile b/infinite_tracing/Rakefile index 047b155cd0..63b4a85007 100644 --- a/infinite_tracing/Rakefile +++ b/infinite_tracing/Rakefile @@ -20,5 +20,5 @@ Rake::TestTask.new do |t| t.libs << "#{ROOT}/test" t.libs << "#{ROOT}/lib" t.pattern = Array(file_pattern).join(",") - t.verbose = ENV["VERBOSE"] + t.verbose = ENV["VERBOSE"] end diff --git a/infinite_tracing/lib/infinite_tracing.rb b/infinite_tracing/lib/infinite_tracing.rb index c355ae77ef..69cb9b4ca7 100644 --- a/infinite_tracing/lib/infinite_tracing.rb +++ b/infinite_tracing/lib/infinite_tracing.rb @@ -37,4 +37,4 @@ require 'infinite_tracing/agent_integrations' end -end \ No newline at end of file +end diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations.rb index 0b72a8b1f4..b14bfe5159 100644 --- a/infinite_tracing/lib/infinite_tracing/agent_integrations.rb +++ b/infinite_tracing/lib/infinite_tracing/agent_integrations.rb @@ -17,4 +17,4 @@ module InfiniteTracing NewRelic::Agent.logger.debug "Skipped Integrating Infinite Tracer with Agent" end end -end \ No newline at end of file +end diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb index 94b4714bd3..9df77fb7a4 100644 --- a/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb +++ b/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb @@ -5,14 +5,13 @@ module NewRelic::Agent NewRelic::Agent.logger.debug "Installing Infinite Tracer in Agent" - - Agent.class_eval do + Agent.class_eval do def new_infinite_tracer # We must start streaming in a thread or we block/deadlock the # entire start up process for the Agent. - InfiniteTracing::Client.new.tap do |client| - @infinite_tracer_thread = InfiniteTracing::Worker.new(:infinite_tracer) do + InfiniteTracing::Client.new.tap do |client| + @infinite_tracer_thread = InfiniteTracing::Worker.new(:infinite_tracer) do NewRelic::Agent.logger.debug "Opening Infinite Tracer Stream with gRPC server" client.start_streaming end diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations/external_request_segment.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations/external_request_segment.rb index acd658519f..5e19145c18 100644 --- a/infinite_tracing/lib/infinite_tracing/agent_integrations/external_request_segment.rb +++ b/infinite_tracing/lib/infinite_tracing/agent_integrations/external_request_segment.rb @@ -10,7 +10,7 @@ class ExternalRequestSegment def record_span_event # don't record a span event if the transaction is ignored return if transaction.ignore? - + tracer = ::NewRelic::Agent.agent.infinite_tracer tracer << Proc.new { SpanEventPrimitive.for_external_request_segment self } end diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations/segment.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations/segment.rb index 4a2488e528..477b2e5f84 100644 --- a/infinite_tracing/lib/infinite_tracing/agent_integrations/segment.rb +++ b/infinite_tracing/lib/infinite_tracing/agent_integrations/segment.rb @@ -7,7 +7,6 @@ module NewRelic module Agent class Transaction class Segment - def segment_complete record_span_event end diff --git a/infinite_tracing/lib/infinite_tracing/channel.rb b/infinite_tracing/lib/infinite_tracing/channel.rb index 636fd0144b..1afcf29dd6 100644 --- a/infinite_tracing/lib/infinite_tracing/channel.rb +++ b/infinite_tracing/lib/infinite_tracing/channel.rb @@ -6,23 +6,22 @@ module NewRelic::Agent module InfiniteTracing class Channel - def stub NewRelic::Agent.logger.debug "Infinite Tracer Opening Channel to #{host_and_port}" Com::Newrelic::Trace::V1::IngestService::Stub.new \ - host_and_port, - credentials, + host_and_port, + credentials, channel_override: channel end def channel GRPC::Core::Channel.new(host_and_port, settings, credentials) end - + def credentials if Config.local? - :this_channel_is_insecure + :this_channel_is_insecure else # Uses system configured certificates by default GRPC::Core::ChannelCredentials.new @@ -36,10 +35,9 @@ def host_and_port def settings { 'grpc.minimal_stack' => 1, - 'grpc.enable_deadline_checking' => 0, + 'grpc.enable_deadline_checking' => 0 } end - end end end diff --git a/infinite_tracing/lib/infinite_tracing/client.rb b/infinite_tracing/lib/infinite_tracing/client.rb index f292214488..2ffc5567f5 100644 --- a/infinite_tracing/lib/infinite_tracing/client.rb +++ b/infinite_tracing/lib/infinite_tracing/client.rb @@ -7,9 +7,9 @@ # # Restarting the client will cause a new connection to the gRPC server. # When the client is restarted, a new streaming buffer is started and contents of old -# buffer are transferred to the new buffer. +# buffer are transferred to the new buffer. # -# Suspending the client will prevent the client from attempting to reconnect to the +# Suspending the client will prevent the client from attempting to reconnect to the # gRPC server, but will still continue to record the span events `seen` metric. module NewRelic::Agent module InfiniteTracing @@ -52,7 +52,7 @@ def flush # Turns camelcase base class name into upper snake case version of the name. def formatted_class_name class_name class_name = class_name.split(":")[-1] - formatted_class_name = (class_name.gsub!(/(.)([A-Z])/,'\1_\2') || class_name).upcase + formatted_class_name = (class_name.gsub!(/(.)([A-Z])/, '\1_\2') || class_name).upcase end # Literal codes are all mapped to unique class names, so we can deduce the @@ -91,7 +91,7 @@ def suspended? # This method is called when the server closes the record status stream without # raising an error. The Channel/Connection is not closed or reset in this case. - # We simply start streaming again, which will reuse the channel/connection to the + # We simply start streaming again, which will reuse the channel/connection to the # server and re-establish the gRPC bi-directional stream. Useful for the server # to initiate a load-balancing scheme. def handle_close @@ -100,7 +100,7 @@ def handle_close start_streaming end - # Places the client into suspended state whereby client will no longer attempt to + # Places the client into suspended state whereby client will no longer attempt to # reconnect to the gRPC server nor will it attempt to send span events henceforth. # The Suspended Streaming Buffer will be installed in this state. def suspend @@ -141,7 +141,7 @@ def stop end end - def start_streaming exponential_backoff=true + def start_streaming exponential_backoff = true return if suspended? Connection.instance.wait_for_agent_connect @lock.synchronize { @response_handler = record_spans exponential_backoff } diff --git a/infinite_tracing/lib/infinite_tracing/config.rb b/infinite_tracing/lib/infinite_tracing/config.rb index 698453b256..802ec1567e 100644 --- a/infinite_tracing/lib/infinite_tracing/config.rb +++ b/infinite_tracing/lib/infinite_tracing/config.rb @@ -24,9 +24,9 @@ def should_load? # AND the collect_span_events connect response field, AND # c) A Trace Observer host is configured by setting infinite_tracing.trace_observer.host. def enabled? - distributed_tracing_enabled? && - span_events_enabled? && - trace_observer_configured? + distributed_tracing_enabled? && + span_events_enabled? && + trace_observer_configured? end # Distributed Tracing must be enabled for Infinite Tracing @@ -39,9 +39,9 @@ def span_events_enabled? NewRelic::Agent.config[:'span_events.enabled'] end - # running locally is akin to communicating with the gRPC server with an + # running locally is akin to communicating with the gRPC server with an # unencrypted channel. Generally, this is _not_ allowed by the agent - # in normal use-cases. The only known use-case for this is when + # in normal use-cases. The only known use-case for this is when # streaming under TEST conditions. def local? test_framework? @@ -74,7 +74,7 @@ def trace_observer_port port_from_host_entry || NewRelic::Agent.config[:'infinite_tracing.trace_observer.port'] end - # The scheme is based on whether the Trace Observer is running locally or remotely. + # The scheme is based on whether the Trace Observer is running locally or remotely. # Remote unsecure (unencypted) streaming is disallowed! def trace_observer_scheme local? ? NewRelic::HTTP : NewRelic::HTTPS @@ -95,7 +95,7 @@ def trace_observer_host_and_port "#{trace_observer_host}:#{trace_observer_port}" end - # The maximum number of span events the Streaming Buffer can hold when buffering + # The maximum number of span events the Streaming Buffer can hold when buffering # to stream across the gRPC channel. def span_events_queue_size NewRelic::Agent.config[:'span_events.queue_size'] diff --git a/infinite_tracing/lib/infinite_tracing/connection.rb b/infinite_tracing/lib/infinite_tracing/connection.rb index 02b88b2b22..8f397aade5 100644 --- a/infinite_tracing/lib/infinite_tracing/connection.rb +++ b/infinite_tracing/lib/infinite_tracing/connection.rb @@ -18,8 +18,6 @@ module NewRelic::Agent module InfiniteTracing class Connection - - # listens for server side configurations added to the agent. When a new config is # added, we have a new agent run token and need to restart the client's RPC stream # with the new metadata information. @@ -34,7 +32,6 @@ class Connection end class << self - def instance @@instance ||= new end @@ -65,8 +62,8 @@ def metadata # We attempt to connect and record spans with reconnection backoff in order to deal with # unavailable errors coming from the stub being created and record_span call def record_spans client, enumerator, exponential_backoff - @active_clients[client] = client - with_reconnection_backoff(exponential_backoff) { rpc.record_span enumerator, metadata: metadata } + @active_clients[client] = client + with_reconnection_backoff(exponential_backoff) { rpc.record_span enumerator, metadata: metadata } end # RPC calls will pass the calling client instance in. We track this @@ -84,7 +81,7 @@ def rpc wait_for_agent_connect @rpc ||= Channel.new.stub end - + def wait_for_agent_connect @lock.synchronize do @agent_started.wait(@lock) if !@agent_connected @@ -98,7 +95,6 @@ def metadata return @metadata if @metadata @lock.synchronize do - @metadata = { "license_key" => license_key, "agent_run_token" => agent_id @@ -152,7 +148,7 @@ def request_headers_map end # Continues retrying the connection at backoff intervals until a successful connection is made - def with_reconnection_backoff exponential_backoff=true, &block + def with_reconnection_backoff exponential_backoff = true, &block @connection_attempts = 0 begin yield @@ -166,7 +162,7 @@ def with_reconnection_backoff exponential_backoff=true, &block end end - def retry_connection_period exponential_backoff=true + def retry_connection_period exponential_backoff = true if exponential_backoff NewRelic::CONNECT_RETRY_PERIODS[@connection_attempts] || NewRelic::MAX_RETRY_PERIOD else @@ -178,7 +174,6 @@ def retry_connection_period exponential_backoff=true def note_connect_failure @connection_attempts += 1 end - end end end diff --git a/infinite_tracing/lib/infinite_tracing/constants.rb b/infinite_tracing/lib/infinite_tracing/constants.rb index aa0f591de3..8159b05b13 100644 --- a/infinite_tracing/lib/infinite_tracing/constants.rb +++ b/infinite_tracing/lib/infinite_tracing/constants.rb @@ -6,14 +6,14 @@ module NewRelic::Agent module InfiniteTracing module Constants - SUPPORTABILITY_PREFIX = "Supportability/InfiniteTracing/Span" + SUPPORTABILITY_PREFIX = "Supportability/InfiniteTracing/Span" - SPANS_SEEN_METRIC = "#{SUPPORTABILITY_PREFIX}/Seen" - SPANS_SENT_METRIC = "#{SUPPORTABILITY_PREFIX}/Sent" - QUEUE_DUMPED_METRIC = "#{SUPPORTABILITY_PREFIX}/AgentQueueDumped" - RESPONSE_ERROR_METRIC = "#{SUPPORTABILITY_PREFIX}/Response/Error" + SPANS_SEEN_METRIC = "#{SUPPORTABILITY_PREFIX}/Seen" + SPANS_SENT_METRIC = "#{SUPPORTABILITY_PREFIX}/Sent" + QUEUE_DUMPED_METRIC = "#{SUPPORTABILITY_PREFIX}/AgentQueueDumped" + RESPONSE_ERROR_METRIC = "#{SUPPORTABILITY_PREFIX}/Response/Error" - GRPC_ERROR_NAME_METRIC = "#{SUPPORTABILITY_PREFIX}/gRPC/%s" + GRPC_ERROR_NAME_METRIC = "#{SUPPORTABILITY_PREFIX}/gRPC/%s" GRPC_OTHER_ERROR_METRIC = GRPC_ERROR_NAME_METRIC % "Other" end end diff --git a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb index 0dd251e360..563c34501a 100644 --- a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb +++ b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb @@ -6,7 +6,6 @@ # Generated by the protocol buffer compiler. DO NOT EDIT! # source: infinite_tracing.proto - Google::Protobuf::DescriptorPool.generated_pool.build do add_message "com.newrelic.trace.v1.SpanBatch" do repeated :spans, :message, 1, "com.newrelic.trace.v1.Span" diff --git a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_services_pb.rb b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_services_pb.rb index dde83af01b..1f78d6d787 100644 --- a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_services_pb.rb +++ b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_services_pb.rb @@ -11,14 +11,12 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # - module Com module Newrelic module Trace module V1 module IngestService class Service - include GRPC::GenericService self.marshal_class_method = :encode diff --git a/infinite_tracing/lib/infinite_tracing/record_status_handler.rb b/infinite_tracing/lib/infinite_tracing/record_status_handler.rb index e42877345d..72fba4c705 100644 --- a/infinite_tracing/lib/infinite_tracing/record_status_handler.rb +++ b/infinite_tracing/lib/infinite_tracing/record_status_handler.rb @@ -48,4 +48,4 @@ def stop end end end -end \ No newline at end of file +end diff --git a/infinite_tracing/lib/infinite_tracing/streaming_buffer.rb b/infinite_tracing/lib/infinite_tracing/streaming_buffer.rb index dcd507c761..daab002829 100644 --- a/infinite_tracing/lib/infinite_tracing/streaming_buffer.rb +++ b/infinite_tracing/lib/infinite_tracing/streaming_buffer.rb @@ -7,7 +7,6 @@ # class. The enumerator is blocking while the queue is empty. module NewRelic::Agent module InfiniteTracing - BATCH_SIZE = 100 class StreamingBuffer @@ -17,8 +16,8 @@ class StreamingBuffer def_delegators :@queue, :empty?, :num_waiting, :push DEFAULT_QUEUE_SIZE = 10_000 - FLUSH_DELAY = 0.005 - MAX_FLUSH_WAIT = 3 # three seconds + FLUSH_DELAY = 0.005 + MAX_FLUSH_WAIT = 3 # three seconds attr_reader :queue @@ -148,7 +147,6 @@ def span_event proc_or_segment def transform proc_or_segment Span.new Transformer.transform(span_event proc_or_segment) end - end end end diff --git a/infinite_tracing/lib/infinite_tracing/suspended_streaming_buffer.rb b/infinite_tracing/lib/infinite_tracing/suspended_streaming_buffer.rb index c5b4f9a6ed..c370f4802a 100644 --- a/infinite_tracing/lib/infinite_tracing/suspended_streaming_buffer.rb +++ b/infinite_tracing/lib/infinite_tracing/suspended_streaming_buffer.rb @@ -3,8 +3,8 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -# The SuspendedStreamingBuffer class discards pushed segments and records -# the seen metric. This buffer is installed when the gRPC server returns +# The SuspendedStreamingBuffer class discards pushed segments and records +# the seen metric. This buffer is installed when the gRPC server returns # UNIMPLEMENTED (status 12) code as a signal to not reconnect to the server. module NewRelic::Agent module InfiniteTracing @@ -30,7 +30,7 @@ def close_queue # NOOP end alias :flush_queue :close_queue - + def enumerator @empty_buffer end diff --git a/infinite_tracing/lib/infinite_tracing/transformer.rb b/infinite_tracing/lib/infinite_tracing/transformer.rb index 12dcbabf08..074ca41a16 100644 --- a/infinite_tracing/lib/infinite_tracing/transformer.rb +++ b/infinite_tracing/lib/infinite_tracing/transformer.rb @@ -25,15 +25,15 @@ def transform span_event TrueClass => :bool_value, FalseClass => :bool_value, Integer => :int_value, - Float => :double_value, + Float => :double_value } if RUBY_VERSION < '2.4.0' KLASS_TO_ARG[Fixnum] = :int_value end if defined? BigDecimal - KLASS_TO_ARG[BigDecimal] = :double_value + KLASS_TO_ARG[BigDecimal] = :double_value end - + def safe_param_name value KLASS_TO_ARG[value.class] || raise("Unhandled class #{value.class.name}") end @@ -51,4 +51,4 @@ def hash_to_attributes values end end end -end \ No newline at end of file +end diff --git a/infinite_tracing/lib/infinite_tracing/worker.rb b/infinite_tracing/lib/infinite_tracing/worker.rb index f1408e0708..b9687e4122 100644 --- a/infinite_tracing/lib/infinite_tracing/worker.rb +++ b/infinite_tracing/lib/infinite_tracing/worker.rb @@ -4,12 +4,11 @@ # frozen_string_literal: true # The Worker class makes it easy to stop and start a thread at will. -# Some basic error handling/capture is wrapped around the Thread to help +# Some basic error handling/capture is wrapped around the Thread to help # propagate the exceptions arising from the threaded processes to the main process # where the main agent code lives. module NewRelic::Agent module InfiniteTracing - class Worker attr_reader :name, :error @@ -34,14 +33,14 @@ def error? !!@error end - def join timeout=nil + def join timeout = nil return unless @worker_thread NewRelic::Agent.logger.debug "joining worker #{@name} thread..." - @worker_thread.join timeout + @worker_thread.join timeout end def stop - @lock.synchronize do + @lock.synchronize do return unless @worker_thread NewRelic::Agent.logger.debug "stopping worker #{@name} thread..." @worker_thread.kill @@ -69,6 +68,5 @@ def start_thread end end end - end -end \ No newline at end of file +end diff --git a/infinite_tracing/lib/new_relic/infinite_tracing.rb b/infinite_tracing/lib/new_relic/infinite_tracing.rb index 4a8714a357..09042bf3ee 100644 --- a/infinite_tracing/lib/new_relic/infinite_tracing.rb +++ b/infinite_tracing/lib/new_relic/infinite_tracing.rb @@ -37,4 +37,4 @@ require 'new_relic/infinite_tracing/agent_integrations' end -end \ No newline at end of file +end diff --git a/infinite_tracing/lib/newrelic/infinite_tracing.rb b/infinite_tracing/lib/newrelic/infinite_tracing.rb index 4a1ffce75f..756607e596 100644 --- a/infinite_tracing/lib/newrelic/infinite_tracing.rb +++ b/infinite_tracing/lib/newrelic/infinite_tracing.rb @@ -5,4 +5,4 @@ unless defined? NewRelic::Agent::InfiniteTracing require_relative '../infinite_tracing' -end \ No newline at end of file +end diff --git a/infinite_tracing/newrelic-infinite_tracing.gemspec b/infinite_tracing/newrelic-infinite_tracing.gemspec index 07f18cb155..72448d620d 100644 --- a/infinite_tracing/newrelic-infinite_tracing.gemspec +++ b/infinite_tracing/newrelic-infinite_tracing.gemspec @@ -12,7 +12,6 @@ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'new_relic/version' Gem::Specification.new do |s| - def self.copy_files filelist subfolder = File.expand_path File.dirname(__FILE__) @@ -25,7 +24,7 @@ Gem::Specification.new do |s| shared_files = [ "../LICENSE", - "../CONTRIBUTING.md", + "../CONTRIBUTING.md" ] self.copy_files shared_files @@ -34,8 +33,7 @@ Gem::Specification.new do |s| s.version = NewRelic::VERSION::STRING s.required_ruby_version = '>= 2.5.0' s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= - s.authors = [ "Tanna McClure", "Kayla Reopelle" ] - s.date = Time.now.strftime('%Y-%m-%d') + s.authors = ["Tanna McClure", "Kayla Reopelle"] s.licenses = ['Apache-2.0'] s.description = <<-EOS The New Relic Ruby agent requires the gem newrelic_rpm, and it includes distributed @@ -50,7 +48,7 @@ Inc (http://www.newrelic.com). New Relic provides you with deep information about the performance of your web application as it runs in production. The New Relic Ruby Agent is dual-purposed as a either a Gem or plugin, hosted on https://github.com/newrelic/newrelic-ruby-agent/ -EOS + EOS s.email = "support@newrelic.com" s.executables = [] @@ -60,11 +58,11 @@ EOS ] s.metadata = { - 'bug_tracker_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/issues', - 'changelog_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/blob/main/infinite_tracing/CHANGELOG.md', + 'bug_tracker_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/issues', + 'changelog_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/blob/main/infinite_tracing/CHANGELOG.md', 'documentation_uri' => 'https://docs.newrelic.com/docs/agents/ruby-agent', - 'source_code_uri' => 'https://github.com/newrelic/newrelic-ruby-agent', - "homepage_uri" => "https://newrelic.com/products/edge-infinite-tracing", + 'source_code_uri' => 'https://github.com/newrelic/newrelic-ruby-agent', + "homepage_uri" => "https://newrelic.com/products/edge-infinite-tracing" } file_list = `git ls-files . -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/(?!agent_helper.rb)}) } @@ -79,8 +77,8 @@ EOS s.add_dependency 'grpc', '~> 1.34' s.add_development_dependency 'rake', '12.3.3' - s.add_development_dependency 'rb-inotify', '0.9.10' # locked to support < Ruby 2.3 (and listen 3.0.8) - s.add_development_dependency 'listen', '3.0.8' # locked to support < Ruby 2.3 + s.add_development_dependency 'rb-inotify', '0.9.10' # locked to support < Ruby 2.3 (and listen 3.0.8) + s.add_development_dependency 'listen', '3.0.8' # locked to support < Ruby 2.3 s.add_development_dependency 'minitest', '~> 5.14.0' s.add_development_dependency 'mocha', '~> 1.9.0' s.add_development_dependency 'pry-nav', '~> 0.3.0' diff --git a/infinite_tracing/tasks/all.rb b/infinite_tracing/tasks/all.rb index 56ca4ee102..ca5ad9086a 100644 --- a/infinite_tracing/tasks/all.rb +++ b/infinite_tracing/tasks/all.rb @@ -3,6 +3,6 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # This is required to load in task definitions -Dir.glob(File.join(File.dirname(__FILE__),'*.rake')) do |file| +Dir.glob(File.join(File.dirname(__FILE__), '*.rake')) do |file| load file end diff --git a/infinite_tracing/tasks/proto.rake b/infinite_tracing/tasks/proto.rake index 5d20cd7c25..7c61bcf372 100644 --- a/infinite_tracing/tasks/proto.rake +++ b/infinite_tracing/tasks/proto.rake @@ -20,7 +20,7 @@ namespace :proto do license_terms = extract_license_terms File.readlines(File.join(gemspec_path, "Gemfile")) Dir.glob(File.join output_path, "*.rb") do |filename| contents = File.readlines filename - contents.reject!{|r| r =~ /^\s*require\s.*$/} + contents.reject! { |r| r =~ /^\s*require\s.*$/ } File.open(filename, 'w') do |output| output.puts license_terms output.puts contents @@ -47,5 +47,4 @@ namespace :proto do puts "Failed to generate proto file." end end - end diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb index 09567c1d6b..d73a36352b 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb @@ -47,7 +47,6 @@ def test_streams_multiple_segments assert_equal total_spans, segments.size end end - ensure Connection.instance.unstub(:retry_connection_period) NewRelic::Agent.agent.infinite_tracer.stop diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb index 2b5ff13e58..22f7174de6 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb @@ -12,15 +12,14 @@ class DataStoreSegmentIntegrationTest < Minitest::Test include FakeTraceObserverHelpers def test_sampled_segment_records_span_event - trace_id = nil - txn_guid = nil - sampled = nil - priority = nil - timestamp = nil + trace_id = nil + txn_guid = nil + sampled = nil + priority = nil + timestamp = nil sql_statement = "select * from table" span_events = generate_and_stream_segments do - in_web_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) @@ -30,7 +29,7 @@ def test_sampled_segment_records_span_event operation: "select", host: "rachel.foo", port_path_or_id: 1337807, - database_name: "calzone_zone", + database_name: "calzone_zone" ) segment.notice_sql sql_statement @@ -41,39 +40,39 @@ def test_sampled_segment_records_span_event trace_id = txn.trace_id txn_guid = txn.guid - sampled = txn.sampled? + sampled = txn.sampled? priority = txn.priority end end assert_equal 2, span_events.size - intrinsics = span_events[0]['intrinsics'] - agent_attributes = span_events[0]['agent_attributes'] + intrinsics = span_events[0]['intrinsics'] + agent_attributes = span_events[0]['agent_attributes'] - root_span_event = span_events[1] - root_guid = root_span_event['intrinsics']['guid'].string_value + root_span_event = span_events[1] + root_guid = root_span_event['intrinsics']['guid'].string_value datastore = 'Datastore/statement/SQLite/Blahg/select' - assert_equal 'Span', intrinsics['type'].string_value - assert_equal trace_id, intrinsics['traceId'].string_value - refute intrinsics['guid'].string_value.empty? - assert_equal root_guid, intrinsics['parentId'].string_value - assert_equal txn_guid, intrinsics['transactionId'].string_value - assert_equal sampled, intrinsics['sampled'].bool_value - assert_equal priority, intrinsics['priority'].double_value - assert_equal timestamp, intrinsics['timestamp'].int_value - assert_equal 1.0, intrinsics['duration'].double_value - assert_equal datastore, intrinsics['name'].string_value + assert_equal 'Span', intrinsics['type'].string_value + assert_equal trace_id, intrinsics['traceId'].string_value + refute intrinsics['guid'].string_value.empty? + assert_equal root_guid, intrinsics['parentId'].string_value + assert_equal txn_guid, intrinsics['transactionId'].string_value + assert_equal sampled, intrinsics['sampled'].bool_value + assert_equal priority, intrinsics['priority'].double_value + assert_equal timestamp, intrinsics['timestamp'].int_value + assert_equal 1.0, intrinsics['duration'].double_value + assert_equal datastore, intrinsics['name'].string_value assert_equal 'datastore', intrinsics['category'].string_value - assert_equal 'SQLite', intrinsics['component'].string_value - assert_equal 'client', intrinsics['span.kind'].string_value + assert_equal 'SQLite', intrinsics['component'].string_value + assert_equal 'client', intrinsics['span.kind'].string_value - assert_equal 'calzone_zone', agent_attributes['db.instance'].string_value + assert_equal 'calzone_zone', agent_attributes['db.instance'].string_value assert_equal 'rachel.foo:1337807', agent_attributes['peer.address'].string_value - assert_equal 'rachel.foo', agent_attributes['peer.hostname'].string_value - assert_equal sql_statement, agent_attributes['db.statement'].string_value + assert_equal 'rachel.foo', agent_attributes['peer.hostname'].string_value + assert_equal sql_statement, agent_attributes['db.statement'].string_value end def test_non_sampled_segment_does_record_span_event diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb index 95925f68ef..b1bbf70ed8 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb @@ -12,12 +12,12 @@ class ExternalRequestSegmentIntegrationTest < Minitest::Test include FakeTraceObserverHelpers def test_sampled_external_records_span_event - trace_id = nil - txn_guid = nil - sampled = nil - priority = nil + trace_id = nil + txn_guid = nil + sampled = nil + priority = nil timestamp = nil - segment = nil + segment = nil span_events = generate_and_stream_segments do in_transaction('wat') do |txn| @@ -37,33 +37,33 @@ def test_sampled_external_records_span_event trace_id = txn.trace_id txn_guid = txn.guid - sampled = txn.sampled? + sampled = txn.sampled? priority = txn.priority end end assert_equal 2, span_events.size - external_intrinsics = span_events[0]['intrinsics'] + external_intrinsics = span_events[0]['intrinsics'] external_agent_attributes = span_events[0]['agent_attributes'] - root_span_event = span_events[1]['intrinsics'] - root_guid = root_span_event['guid'].string_value + root_span_event = span_events[1]['intrinsics'] + root_guid = root_span_event['guid'].string_value expected_name = 'External/remotehost.com/Typhoeus/GET' - assert_equal 'Span', external_intrinsics['type'].string_value - assert_equal trace_id, external_intrinsics['traceId'].string_value - refute_nil external_intrinsics['guid'].string_value - assert_equal root_guid, external_intrinsics['parentId'].string_value - assert_equal txn_guid, external_intrinsics['transactionId'].string_value - assert_equal sampled, external_intrinsics['sampled'].bool_value - assert_equal priority, external_intrinsics['priority'].double_value - assert_equal timestamp, external_intrinsics['timestamp'].int_value - assert_equal 1.0, external_intrinsics['duration'].double_value - assert_equal expected_name, external_intrinsics['name'].string_value - assert_equal segment.library, external_intrinsics['component'].string_value + assert_equal 'Span', external_intrinsics['type'].string_value + assert_equal trace_id, external_intrinsics['traceId'].string_value + refute_nil external_intrinsics['guid'].string_value + assert_equal root_guid, external_intrinsics['parentId'].string_value + assert_equal txn_guid, external_intrinsics['transactionId'].string_value + assert_equal sampled, external_intrinsics['sampled'].bool_value + assert_equal priority, external_intrinsics['priority'].double_value + assert_equal timestamp, external_intrinsics['timestamp'].int_value + assert_equal 1.0, external_intrinsics['duration'].double_value + assert_equal expected_name, external_intrinsics['name'].string_value + assert_equal segment.library, external_intrinsics['component'].string_value assert_equal segment.procedure, external_intrinsics['http.method'].string_value - assert_equal 'http', external_intrinsics['category'].string_value - assert_equal segment.uri.to_s, external_agent_attributes['http.url'].string_value + assert_equal 'http', external_intrinsics['category'].string_value + assert_equal segment.uri.to_s, external_agent_attributes['http.url'].string_value end def test_non_sampled_segment_does_record_span_event @@ -73,8 +73,8 @@ def test_non_sampled_segment_does_record_span_event segment = Transaction::ExternalRequestSegment.new \ "Typhoeus", - "http://remotehost.com/blogs/index", - "GET" + "http://remotehost.com/blogs/index", + "GET" txn.add_segment segment segment.start @@ -93,8 +93,8 @@ def test_ignored_transaction_does_not_record_span_event segment = Transaction::ExternalRequestSegment.new \ "Typhoeus", - "http://remotehost.com/blogs/index", - "GET" + "http://remotehost.com/blogs/index", + "GET" txn.add_segment segment segment.start diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/segment_test.rb index dcfe1f44fd..da0b7bd7ed 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/segment_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/segment_test.rb @@ -12,10 +12,10 @@ class SegmentIntegrationTest < Minitest::Test include FakeTraceObserverHelpers def test_sampled_segment_records_span_event - trace_id = nil - txn_guid = nil - sampled = nil - priority = nil + trace_id = nil + txn_guid = nil + sampled = nil + priority = nil timestamp = nil span_events = generate_and_stream_segments do @@ -32,7 +32,7 @@ def test_sampled_segment_records_span_event trace_id = txn.trace_id txn_guid = txn.guid - sampled = txn.sampled? + sampled = txn.sampled? priority = txn.priority end end @@ -40,19 +40,19 @@ def test_sampled_segment_records_span_event assert_equal 2, span_events.size custom_span_event = span_events[0] - root_span_event = span_events[1] - root_guid = root_span_event['intrinsics']['guid'].string_value + root_span_event = span_events[1] + root_guid = root_span_event['intrinsics']['guid'].string_value - assert_equal 'Span', custom_span_event['intrinsics']['type'].string_value - assert_equal trace_id, custom_span_event['intrinsics']['traceId'].string_value - refute custom_span_event['intrinsics']['guid'].string_value.empty? + assert_equal 'Span', custom_span_event['intrinsics']['type'].string_value + assert_equal trace_id, custom_span_event['intrinsics']['traceId'].string_value + refute custom_span_event['intrinsics']['guid'].string_value.empty? assert_equal root_guid, custom_span_event['intrinsics']['parentId'].string_value - assert_equal txn_guid, custom_span_event['intrinsics']['transactionId'].string_value - assert_equal sampled, custom_span_event['intrinsics']['sampled'].bool_value - assert_equal priority, custom_span_event['intrinsics']['priority'].double_value + assert_equal txn_guid, custom_span_event['intrinsics']['transactionId'].string_value + assert_equal sampled, custom_span_event['intrinsics']['sampled'].bool_value + assert_equal priority, custom_span_event['intrinsics']['priority'].double_value assert_equal timestamp, custom_span_event['intrinsics']['timestamp'].int_value - assert_equal 1.0, custom_span_event['intrinsics']['duration'].double_value - assert_equal 'Ummm', custom_span_event['intrinsics']['name'].string_value + assert_equal 1.0, custom_span_event['intrinsics']['duration'].double_value + assert_equal 'Ummm', custom_span_event['intrinsics']['name'].string_value assert_equal 'generic', custom_span_event['intrinsics']['category'].string_value end diff --git a/infinite_tracing/test/infinite_tracing/channel_test.rb b/infinite_tracing/test/infinite_tracing/channel_test.rb index e128ac676f..0b979ac683 100644 --- a/infinite_tracing/test/infinite_tracing/channel_test.rb +++ b/infinite_tracing/test/infinite_tracing/channel_test.rb @@ -9,17 +9,16 @@ module NewRelic module Agent module InfiniteTracing class ChannelTest < Minitest::Test - - def local_config - { + def local_config + { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, :'infinite_tracing.trace_observer.host' => "localhost:80" } end - def remote_config - { + def remote_config + { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, :'infinite_tracing.trace_observer.host' => "https://example.com" @@ -30,7 +29,7 @@ def test_channel_is_insecure_for_local_host with_config local_config do channel = Channel.new credentials = channel.send(:credentials) - + assert_equal "localhost:80", channel.send(:host_and_port) assert_equal :this_channel_is_insecure, credentials end @@ -42,11 +41,10 @@ def test_channel_is_secure_for_remote_host with_config remote_config do channel = Channel.new credentials = channel.send(:credentials) - + assert_equal "example.com:443", channel.send(:host_and_port) assert_kind_of GRPC::Core::ChannelCredentials, credentials end - ensure Config.unstub(:test_framework?) end @@ -61,15 +59,13 @@ def test_channel_is_really_secure_for_remote_host with_config insecure_remote_config do channel = Channel.new credentials = channel.send(:credentials) - + assert_equal "example.com:443", channel.send(:host_and_port) assert_kind_of GRPC::Core::ChannelCredentials, credentials end - ensure Config.unstub(:test_framework?) end - end end end diff --git a/infinite_tracing/test/infinite_tracing/client_test.rb b/infinite_tracing/test/infinite_tracing/client_test.rb index 5948f46d7f..febe4c0480 100644 --- a/infinite_tracing/test/infinite_tracing/client_test.rb +++ b/infinite_tracing/test/infinite_tracing/client_test.rb @@ -33,7 +33,7 @@ def test_streams_multiple_segments end def test_streams_across_reconnects - with_serial_lock do + with_serial_lock do NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') total_spans = 5 spans, segments = emulate_streaming_segments total_spans do |client, segments| @@ -45,8 +45,8 @@ def test_streams_across_reconnects assert_equal total_spans, segments.size assert_equal total_spans, spans.size - span_ids = spans.map{|s| s["trace_id"]}.sort - segment_ids = segments.map{|s| s.transaction.trace_id}.sort + span_ids = spans.map { |s| s["trace_id"] }.sort + segment_ids = segments.map { |s| s.transaction.trace_id }.sort assert_equal segment_ids, span_ids @@ -59,7 +59,7 @@ def test_streams_across_reconnects end def test_handles_server_disconnects - with_serial_lock do + with_serial_lock do unstub_reconnection Connection.any_instance.stubs(:retry_connection_period).returns(0) NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') @@ -76,8 +76,8 @@ def test_handles_server_disconnects assert_equal total_spans, segments.size assert_equal total_spans, spans.size - span_ids = spans.map{|s| s["trace_id"]}.sort - segment_ids = segments.map{|s| s.transaction.trace_id}.sort + span_ids = spans.map { |s| s["trace_id"] }.sort + segment_ids = segments.map { |s| s.transaction.trace_id }.sort assert_equal segment_ids, span_ids @@ -90,7 +90,7 @@ def test_handles_server_disconnects end def test_handles_server_error_responses - with_serial_lock do + with_serial_lock do NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') connection = Connection.instance connection.stubs(:retry_connection_period).returns(0) @@ -108,7 +108,7 @@ def test_handles_server_error_responses end def test_handles_suspended_state - with_serial_lock do + with_serial_lock do NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') connection = Connection.instance connection.stubs(:retry_connection_period).returns(0) @@ -132,7 +132,7 @@ def test_handles_suspended_state end def test_stores_spans_when_not_connected - with_serial_lock do + with_serial_lock do NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') client = Client.new @@ -145,7 +145,6 @@ def test_stores_spans_when_not_connected assert_equal 5, client.buffer.queue.length end end - end end end diff --git a/infinite_tracing/test/infinite_tracing/config_test.rb b/infinite_tracing/test/infinite_tracing/config_test.rb index c230e3093d..9e32318ecd 100644 --- a/infinite_tracing/test/infinite_tracing/config_test.rb +++ b/infinite_tracing/test/infinite_tracing/config_test.rb @@ -31,7 +31,7 @@ def test_trace_observer_host_normalizes 'example.com', 'http://example.com', 'https://example.com', - 'https://example.com:443', + 'https://example.com:443' ] hostnames.each do |hostname| with_config(:'infinite_tracing.trace_observer.host' => hostname) do @@ -47,7 +47,7 @@ def test_trace_observer_port_from_host_entry ['example.com', 443], ['http://example.com', 443], ['https://example.com', 443], - ['https://example.com:80', 80], + ['https://example.com:80', 80] ] hostnames.each do |hostname, port| with_config(:'infinite_tracing.trace_observer.host' => hostname) do @@ -63,12 +63,12 @@ def test_trace_observer_port_overridden_by_port_from_host_entry ['example.com', 443], ['http://example.com', 443], ['https://example.com', 443], - ['https://example.com:80', 80], + ['https://example.com:80', 80] ] hostnames.each do |hostname, port| config = { :'infinite_tracing.trace_observer.host' => hostname, - :'infinite_tracing.trace_observer.port' => 443, + :'infinite_tracing.trace_observer.port' => 443 } with_config(config) do assert_equal port, Config.trace_observer_port, "expected #{port} for port because host overrides: #{hostname}" @@ -83,15 +83,15 @@ def test_trace_observer_host_and_port ['example.com:443', 'example.com:443'], ['http://example.com', 'example.com:443'], ['https://example.com', 'example.com:443'], - ['https://example.com:80', 'example.com:80'], + ['https://example.com:80', 'example.com:80'] ] hostnames.each do |hostname, host_and_port| config = { - :'infinite_tracing.trace_observer.host' => hostname, + :'infinite_tracing.trace_observer.host' => hostname } with_config(config) do - assert_equal host_and_port, - Config.trace_observer_host_and_port, + assert_equal host_and_port, + Config.trace_observer_host_and_port, "expected #{host_and_port.inspect} when host is: #{hostname.inspect}" end end @@ -110,7 +110,6 @@ def test_unset_trace_observer_host_raises_error def non_test_files all_rb_files.reject { |filename| filename.include? 'test.rb' } end - end end end diff --git a/infinite_tracing/test/infinite_tracing/connection_test.rb b/infinite_tracing/test/infinite_tracing/connection_test.rb index 43217ed6d8..7f4b4fa73d 100644 --- a/infinite_tracing/test/infinite_tracing/connection_test.rb +++ b/infinite_tracing/test/infinite_tracing/connection_test.rb @@ -8,7 +8,6 @@ module NewRelic module Agent module InfiniteTracing - class ConnectionTest < Minitest::Test include FakeTraceObserverHelpers @@ -159,10 +158,10 @@ def test_handling_failed_precondition_server_response def test_handling_ok_and_close_server_response timeout_cap 5 do - with_detailed_trace do + with_detailed_trace do total_spans = 5 expects_logging(:debug, all_of(includes("closed the stream"), includes("OK response.")), anything) - + spans, segments = emulate_streaming_with_ok_close_response(total_spans) do |client, segments, server| server.wait_for_notice end @@ -201,7 +200,7 @@ def test_metadata_includes_request_headers_map with_serial_lock do timeout_cap do with_config localhost_config do - NewRelic::Agent.agent.service.instance_variable_set(:@request_headers_map, {"NR-UtilizationMetadata"=>"test_metadata"}) + NewRelic::Agent.agent.service.instance_variable_set(:@request_headers_map, {"NR-UtilizationMetadata" => "test_metadata"}) connection = Connection.instance # instantiate before simulation simulate_connect_to_collector fiddlesticks_config, 0.01 do |simulator| @@ -218,10 +217,10 @@ def test_metadata_includes_request_headers_map # Testing the backoff similarly to connect_test.rb def test_increment_retry_period unstub_reconnection - assert_equal 15, next_retry_period - assert_equal 15, next_retry_period - assert_equal 30, next_retry_period - assert_equal 60, next_retry_period + assert_equal 15, next_retry_period + assert_equal 15, next_retry_period + assert_equal 30, next_retry_period + assert_equal 60, next_retry_period assert_equal 120, next_retry_period assert_equal 300, next_retry_period assert_equal 300, next_retry_period @@ -235,7 +234,6 @@ def next_retry_period Connection.instance.send(:note_connect_failure) result end - end end end diff --git a/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb b/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb index 7e656812f8..6f09629b7e 100644 --- a/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb +++ b/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb @@ -7,7 +7,6 @@ module NewRelic::Agent::InfiniteTracing class RecordStatusHandlerTest < Minitest::Test - def process_queue handler, queue Thread.pass until queue.empty? handler.stop @@ -23,7 +22,7 @@ def test_processes_single_item_and_stops end def test_processes_multiple_items_and_stops - items = 5.times.map{|i| RecordStatus.new(messages_seen: i + 1)} + items = 5.times.map { |i| RecordStatus.new(messages_seen: i + 1) } queue = EnumeratorQueue.new.preload(items) handler = build_handler queue @@ -51,7 +50,7 @@ def test_processes_nil_on_queue assert_equal 0, handler.messages_seen end - private + private class TestClient def handle_error error @@ -62,6 +61,5 @@ def handle_error error def build_handler queue RecordStatusHandler.new TestClient.new, queue.each_item end - end end diff --git a/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb b/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb index bd96a17a28..3d56792476 100644 --- a/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb +++ b/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb @@ -9,7 +9,6 @@ module NewRelic module Agent module InfiniteTracing class StreamingBufferTest < Minitest::Test - def setup @threads = {} NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') @@ -179,9 +178,9 @@ def watch_thread name, &block @threads[name] = Thread.new(&block) end - def prepare_to_consume_spans buffer, sleep_delay=0 + def prepare_to_consume_spans buffer, sleep_delay = 0 spans = [] - consumer = watch_thread(:consumer) { buffer.enumerator.each{ |span| spans << span } } + consumer = watch_thread(:consumer) { buffer.enumerator.each { |span| spans << span } } return spans, consumer end @@ -189,10 +188,10 @@ def prepare_to_consume_spans buffer, sleep_delay=0 # pops all the serializable spans off the buffer and returns them. def consume_spans buffer buffer.enumerator.map(&:itself) - end + end # starts a watched thread that will generate segments asynchronously. - def prepare_to_stream_segments count, max_buffer_size=100_000 + def prepare_to_stream_segments count, max_buffer_size = 100_000 buffer = StreamingBuffer.new max_buffer_size segments = [] @@ -212,10 +211,10 @@ def prepare_to_stream_segments count, max_buffer_size=100_000 # Opens a streaming buffer,enqueues count segments to the buffer # closes the queue when done as we assume no more will be # generated and don't want to block indefinitely. - # + # # Returns the buffer with segments on the queue as well # as the segments that were generated separately. - def stream_segments count, max_buffer_size=100_000 + def stream_segments count, max_buffer_size = 100_000 buffer = StreamingBuffer.new max_buffer_size segments = [] @@ -227,13 +226,12 @@ def stream_segments count, max_buffer_size=100_000 end end - # if we don't close, we block the pop + # if we don't close, we block the pop # in the enumerator indefinitely buffer.close_queue return buffer, segments end - end end end diff --git a/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb b/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb index b4431d63f1..b69a944715 100644 --- a/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb +++ b/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb @@ -9,7 +9,6 @@ module NewRelic module Agent module InfiniteTracing class SuspendedStreamingBufferTest < Minitest::Test - def setup @threads = {} NewRelic::Agent::Transaction::Segment.any_instance.stubs('record_span_event') @@ -36,12 +35,11 @@ def test_streams_multiple_segments "Supportability/InfiniteTracing/Span/Sent" ]) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, + "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans} }) assert_watched_threads_finished buffer end - def test_can_close_an_empty_buffer total_spans = 10 generator, buffer, segments = prepare_to_stream_segments total_spans @@ -78,7 +76,7 @@ def test_can_close_an_empty_buffer "Supportability/InfiniteTracing/Span/Sent" ]) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, + "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans} }) assert_watched_threads_finished buffer end @@ -99,9 +97,9 @@ def watch_thread name, &block @threads[name] = Thread.new(&block) end - def prepare_to_consume_spans buffer, sleep_delay=0 + def prepare_to_consume_spans buffer, sleep_delay = 0 spans = [] - consumer = watch_thread(:consumer) { buffer.enumerator.each{ |span| spans << span } } + consumer = watch_thread(:consumer) { buffer.enumerator.each { |span| spans << span } } return spans, consumer end @@ -109,10 +107,10 @@ def prepare_to_consume_spans buffer, sleep_delay=0 # pops all the serializable spans off the buffer and returns them. def consume_spans buffer buffer.enumerator.map(&:itself) - end + end # starts a watched thread that will generate segments asynchronously. - def prepare_to_stream_segments count, max_buffer_size=100_000 + def prepare_to_stream_segments count, max_buffer_size = 100_000 buffer = SuspendedStreamingBuffer.new max_buffer_size segments = [] @@ -132,10 +130,10 @@ def prepare_to_stream_segments count, max_buffer_size=100_000 # Opens a streaming buffer,enqueues count segments to the buffer # closes the queue when done as we assume no more will be # generated and don't want to block indefinitely. - # + # # Returns the buffer with segments on the queue as well # as the segments that were generated separately. - def stream_segments count, max_buffer_size=100_000 + def stream_segments count, max_buffer_size = 100_000 buffer = SuspendedStreamingBuffer.new max_buffer_size segments = [] @@ -147,13 +145,12 @@ def stream_segments count, max_buffer_size=100_000 end end - # if we don't close, we block the pop + # if we don't close, we block the pop # in the enumerator indefinitely buffer.close_queue return buffer, segments end - end end end diff --git a/infinite_tracing/test/infinite_tracing/transformer_test.rb b/infinite_tracing/test/infinite_tracing/transformer_test.rb index 9d754496a2..b2cc698b7e 100644 --- a/infinite_tracing/test/infinite_tracing/transformer_test.rb +++ b/infinite_tracing/test/infinite_tracing/transformer_test.rb @@ -9,7 +9,6 @@ module NewRelic module Agent module InfiniteTracing class TransformerTest < Minitest::Test - def test_transforms_single_span_event span_event = Transformer.transform span_event_fixture :single assert_kind_of Hash, span_event @@ -44,9 +43,7 @@ def test_transforms_single_full_span_event assert_kind_of String, key assert_kind_of AttributeValue, value end - end - end end end diff --git a/infinite_tracing/test/infinite_tracing/worker_test.rb b/infinite_tracing/test/infinite_tracing/worker_test.rb index c6efd537cb..4f82b30f5e 100644 --- a/infinite_tracing/test/infinite_tracing/worker_test.rb +++ b/infinite_tracing/test/infinite_tracing/worker_test.rb @@ -7,7 +7,6 @@ module NewRelic::Agent::InfiniteTracing class ResponseHandlerTest < Minitest::Test - def teardown reset_buffers_and_caches end @@ -32,7 +31,7 @@ def test_worker_handles_errors raise "Oops!" NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Error", 0.0) end - + begin worker.join rescue => err @@ -46,4 +45,4 @@ def test_worker_handles_errors refute_metrics_recorded "Supportability/InfiniteTracing/Error" end end -end \ No newline at end of file +end diff --git a/infinite_tracing/test/infinite_tracing_test.rb b/infinite_tracing/test/infinite_tracing_test.rb index 35ab42461f..27922ea499 100644 --- a/infinite_tracing/test/infinite_tracing_test.rb +++ b/infinite_tracing/test/infinite_tracing_test.rb @@ -9,7 +9,6 @@ module NewRelic module Agent module InfiniteTracing class InfiniteTracingTest < Minitest::Test - # Ensures we're tracking versions against agent's version. def test_version_matches_agent_version refute_nil NewRelic::Agent::InfiniteTracing::VERSION::STRING @@ -23,7 +22,6 @@ def test_span_events_fixtures_load assert_kind_of Hash, span_event[1] assert_kind_of Hash, span_event[2] end - end end end diff --git a/infinite_tracing/test/support/enumerator_queue.rb b/infinite_tracing/test/support/enumerator_queue.rb index 7fc7e88154..179d2bb6b5 100644 --- a/infinite_tracing/test/support/enumerator_queue.rb +++ b/infinite_tracing/test/support/enumerator_queue.rb @@ -13,8 +13,8 @@ def initialize end def preload items - Array(items).each{ |item| @queue.push item } - self + Array(items).each { |item| @queue.push item } + self end def each_item diff --git a/infinite_tracing/test/support/fake_trace_observer.rb b/infinite_tracing/test/support/fake_trace_observer.rb index 539eadf575..4ecbe41bee 100644 --- a/infinite_tracing/test/support/fake_trace_observer.rb +++ b/infinite_tracing/test/support/fake_trace_observer.rb @@ -6,7 +6,6 @@ if NewRelic::Agent::InfiniteTracing::Config.should_load? module NewRelic::Agent::InfiniteTracing - class BaseInfiniteTracer < Com::Newrelic::Trace::V1::IngestService::Service attr_reader :spans attr_reader :seen @@ -41,7 +40,6 @@ def wait_for_notice @noticed.wait(@lock) if !@noticed end end - end class InfiniteTracer < BaseInfiniteTracer @@ -54,7 +52,7 @@ def record_span(record_spans) class OkCloseInfiniteTracer < BaseInfiniteTracer def record_span(record_spans) - record_spans.each{ |span| notice_span span } + record_spans.each { |span| notice_span span } [record_status] end end @@ -104,7 +102,7 @@ def record_span(record_spans) class FakeTraceObserverServer attr_reader :trace_observer, :worker - def initialize(port_no, tracer_class=InfiniteTracer) + def initialize(port_no, tracer_class = InfiniteTracer) @port_no = port_no @tracer_class = tracer_class start @@ -119,7 +117,7 @@ def server_options pool_size: 10, max_waiting_requests: 10, server_args: { - 'grpc.so_reuseport' => 0, # eliminates chance of cross-talks + 'grpc.so_reuseport' => 0 # eliminates chance of cross-talks } } end @@ -135,12 +133,12 @@ def start # A simple debug helper that returns list of server context statuses. # When there are intermittent errors happening, usually, instead of seeing # everything in :stopped state, we'll see one or more server contexts in - # :running state. + # :running state. # # This is our hint to research into what's not being shutdown properly! def running_contexts contexts = FakeTraceObserverHelpers::RUNNING_SERVER_CONTEXTS - contexts.map{|k,v| v}.inspect + contexts.map { |k, v| v }.inspect end def add_http2_port diff --git a/infinite_tracing/test/support/fake_trace_observer_helpers.rb b/infinite_tracing/test/support/fake_trace_observer_helpers.rb index bd7d4ec30c..985d8adbfb 100644 --- a/infinite_tracing/test/support/fake_trace_observer_helpers.rb +++ b/infinite_tracing/test/support/fake_trace_observer_helpers.rb @@ -12,13 +12,12 @@ module Agent class EventListener def still_subscribed event return [] if @events[event].nil? - @events[event].select{|e| e.inspect =~ /infinite_tracing/} + @events[event].select { |e| e.inspect =~ /infinite_tracing/ } end end module InfiniteTracing module FakeTraceObserverHelpers - FAKE_SERVER_PORT = 10_000 def setup @@ -117,21 +116,21 @@ def wait_for_notice # one Thread in a "run" state solves the issues altogether. def wait_for_agent_infinite_tracer_thread_to_close timeout_cap(3.0) do - while Thread.list.select{|t| t.status == "run"}.size > 1 + while Thread.list.select { |t| t.status == "run" }.size > 1 sleep(0.01) end sleep(0.01) end end - def flush count=0 + def flush count = 0 wait_for_agent_infinite_tracer_thread_to_close @lock.synchronize do @flushed = true end end - def restart tracer_class=nil + def restart tracer_class = nil @tracer_class = tracer_class unless tracer_class.nil? flush stop @@ -139,7 +138,7 @@ def restart tracer_class=nil end end - def restart_fake_trace_observer_server context, tracer_class=nil + def restart_fake_trace_observer_server context, tracer_class = nil context.restart tracer_class end @@ -165,21 +164,21 @@ def fake_server_config def fiddlesticks_config { 'agent_run_id' => 'fiddlesticks', - 'agent_config' => { 'transaction_tracer.record_sql' => 'raw' } + 'agent_config' => {'transaction_tracer.record_sql' => 'raw'} } end def reconnect_config { 'agent_run_id' => 'shazbat', - 'agent_config' => { 'transaction_tracer.record_sql' => 'raw' } + 'agent_config' => {'transaction_tracer.record_sql' => 'raw'} } end # simulates applying a server-side config to the agent instance. # the sleep 0.01 allows us to choose whether to join and wait # or set it up and continue with test scenario's flow. - def simulate_connect_to_collector config, delay=0.01 + def simulate_connect_to_collector config, delay = 0.01 thread = Thread.new do sleep delay NewRelic::Agent.instance.stubs(:connected?).returns(true) @@ -238,23 +237,23 @@ def emulate_streaming_with_tracer tracer_class, count, max_buffer_size, &block server.stop unless server.nil? end - def emulate_streaming_segments count, max_buffer_size=100_000, &block + def emulate_streaming_segments count, max_buffer_size = 100_000, &block emulate_streaming_with_tracer InfiniteTracer, count, max_buffer_size, &block end - def emulate_streaming_to_unimplemented count, max_buffer_size=100_000, &block + def emulate_streaming_to_unimplemented count, max_buffer_size = 100_000, &block emulate_streaming_with_tracer UnimplementedInfiniteTracer, count, max_buffer_size, &block end - def emulate_streaming_to_failed_precondition count, max_buffer_size=100_000, &block + def emulate_streaming_to_failed_precondition count, max_buffer_size = 100_000, &block emulate_streaming_with_tracer FailedPreconditionInfiniteTracer, count, max_buffer_size, &block end - def emulate_streaming_with_initial_error count, max_buffer_size=100_000, &block + def emulate_streaming_with_initial_error count, max_buffer_size = 100_000, &block emulate_streaming_with_tracer ErroringInfiniteTracer, count, max_buffer_size, &block end - def emulate_streaming_with_ok_close_response count, max_buffer_size=100_000, &block + def emulate_streaming_with_ok_close_response count, max_buffer_size = 100_000, &block emulate_streaming_with_tracer OkCloseInfiniteTracer, count, max_buffer_size, &block end @@ -295,7 +294,6 @@ def generate_and_stream_segments end end end - end end end diff --git a/infinite_tracing/test/support/record_span_handler.rb b/infinite_tracing/test/support/record_span_handler.rb index f9c117a8a6..63a4c8089e 100644 --- a/infinite_tracing/test/support/record_span_handler.rb +++ b/infinite_tracing/test/support/record_span_handler.rb @@ -6,7 +6,6 @@ module NewRelic::Agent module InfiniteTracing class RecordSpanHandler - HURDLE_INCREMENT = 3 def initialize server, record_spans, id @@ -66,4 +65,4 @@ def stop end end end -end \ No newline at end of file +end diff --git a/infinite_tracing/test/test_helper.rb b/infinite_tracing/test/test_helper.rb index 2f31805d6b..05cc6a0de5 100644 --- a/infinite_tracing/test/test_helper.rb +++ b/infinite_tracing/test/test_helper.rb @@ -37,10 +37,10 @@ module NewRelic; TEST = true; end unless defined? NewRelic::TEST Dir[File.expand_path('../support/*', __FILE__)].each { |f| require f } -def timeout_cap duration=1.0 +def timeout_cap duration = 1.0 Timeout::timeout(duration) { yield } rescue Timeout::Error => error - raise Timeout::Error, "Unexpected timeout occurred after #{duration} seconds. #{error.backtrace.reject{|r| r =~ /gems\/minitest/}.join("\n")}" + raise Timeout::Error, "Unexpected timeout occurred after #{duration} seconds. #{error.backtrace.reject { |r| r =~ /gems\/minitest/ }.join("\n")}" end def deferred_span segment @@ -62,12 +62,12 @@ def with_serial_lock TRACE_POINT_ENABLED = false -def trace +def trace @trace ||= TracePoint.new(:call, :b_call) do |tp| next unless tp.defined_class.to_s =~ /InfiniteTracing/ next unless [ - :record_spans, - :record_span, + :record_spans, + :record_span, :emulate_streaming_with_ok_close_response, :handle_error, :handle_close, @@ -78,7 +78,7 @@ def trace :rpc, :start_streaming, :notice_span, - :wait_for_notice, + :wait_for_notice ].include? tp.method_id p [tp.lineno, tp.defined_class, tp.method_id, tp.event] end @@ -91,6 +91,3 @@ def with_detailed_trace yield end end - - - diff --git a/init.rb b/init.rb index c0dc0f82d3..60031cbb73 100644 --- a/init.rb +++ b/init.rb @@ -18,7 +18,6 @@ # We need it to add dev mode routes after initialization finished. begin - current_config = if defined?(config) config elsif defined?(Rails.configuration) @@ -26,7 +25,6 @@ end NewRelic::Control.instance.init_plugin :config => current_config - rescue => e ::NewRelic::Agent.logger.error "Error initializing New Relic plugin. Agent is disabled.", e end diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 0000000000..e9af6b2fb9 --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,9 @@ +# Lefthook (https://github.com/evilmartians/lefthook) is a git hooks manager +# Install it on your machine by running `gem install lefthook` +pre-commit: + parallel: true + commands: + rubocop: + files: git diff --name-only --staged + glob: "*.rb" + run: rubocop --force-exclusion {files} diff --git a/lib/new_relic/agent.rb b/lib/new_relic/agent.rb index 8e81655e0a..fdd322d8e3 100644 --- a/lib/new_relic/agent.rb +++ b/lib/new_relic/agent.rb @@ -44,7 +44,7 @@ module Agent require 'new_relic/agent/sql_sampler' require 'new_relic/agent/commands/thread_profiler_session' require 'new_relic/agent/error_collector' - require 'new_relic/agent/error_filter' + require 'new_relic/agent/error_filter' require 'new_relic/agent/sampler' require 'new_relic/agent/database' require 'new_relic/agent/database_adapter' @@ -111,19 +111,19 @@ class BackgroundLoadingError < StandardError; end @tracer_queue = [] # The singleton Agent instance. Used internally. - def agent #:nodoc: + def agent # :nodoc: return @agent if @agent NewRelic::Agent.logger.warn("Agent unavailable as it hasn't been started.") NewRelic::Agent.logger.warn(caller.join("\n")) nil end - def agent=(new_instance)#:nodoc: + def agent=(new_instance) # :nodoc: @agent = new_instance add_deferred_method_tracers_now end - alias instance agent #:nodoc: + alias instance agent # :nodoc: # Primary interface to logging is fronted by this accessor # Access via ::NewRelic::Agent.logger @@ -187,7 +187,7 @@ def reset_config # This method is safe to use from any thread. # # @api public - def record_metric(metric_name, value) #THREAD_LOCAL_ACCESS + def record_metric(metric_name, value) # THREAD_LOCAL_ACCESS record_api_supportability_metric(:record_metric) return unless agent @@ -217,14 +217,14 @@ def record_metric(metric_name, value) #THREAD_LOCAL_ACCESS SUPPORTABILITY_INCREMENT_METRIC = 'Supportability/API/increment_metric'.freeze - def increment_metric(metric_name, amount=1) #THREAD_LOCAL_ACCESS + def increment_metric(metric_name, amount = 1) # THREAD_LOCAL_ACCESS return unless agent if amount == 1 metrics = [metric_name, SUPPORTABILITY_INCREMENT_METRIC] - agent.stats_engine.tl_record_unscoped_metrics(metrics) {|stats| stats.increment_count} + agent.stats_engine.tl_record_unscoped_metrics(metrics) { |stats| stats.increment_count } else - agent.stats_engine.tl_record_unscoped_metrics(metric_name) {|stats| stats.increment_count(amount)} - agent.stats_engine.tl_record_unscoped_metrics(SUPPORTABILITY_INCREMENT_METRIC) {|stats| stats.increment_count} + agent.stats_engine.tl_record_unscoped_metrics(metric_name) { |stats| stats.increment_count(amount) } + agent.stats_engine.tl_record_unscoped_metrics(SUPPORTABILITY_INCREMENT_METRIC) { |stats| stats.increment_count } end end @@ -281,7 +281,7 @@ def ignore_error_filter(&block) # # @api public # - def notice_error(exception, options={}) + def notice_error(exception, options = {}) record_api_supportability_metric(:notice_error) Transaction.notice_error(exception, options) @@ -347,9 +347,9 @@ def record_custom_event(event_type, event_attrs) # # @api public # - def manual_start(options={}) + def manual_start(options = {}) raise "Options must be a hash" unless Hash === options - NewRelic::Control.instance.init_plugin({ :agent_enabled => true, :sync_startup => true }.merge(options)) + NewRelic::Control.instance.init_plugin({:agent_enabled => true, :sync_startup => true}.merge(options)) record_api_supportability_metric(:manual_start) end @@ -378,7 +378,7 @@ def manual_start(options={}) # # @api public # - def after_fork(options={}) + def after_fork(options = {}) record_api_supportability_metric(:after_fork) agent.after_fork(options) if agent end @@ -390,7 +390,7 @@ def after_fork(options={}) # # @api public # - def shutdown(options={}) + def shutdown(options = {}) record_api_supportability_metric(:shutdown) agent.shutdown if agent end @@ -512,7 +512,7 @@ def disable_all_tracing # def disable_transaction_tracing Deprecator.deprecate :disable_transaction_tracing, - 'disable_all_tracing or ignore_transaction' + 'disable_all_tracing or ignore_transaction' record_api_supportability_metric(:disable_transaction_tracing) yield end @@ -572,7 +572,7 @@ def tl_is_sql_recorded? # # @api public # - def add_custom_attributes(params) #THREAD_LOCAL_ACCESS + def add_custom_attributes(params) # THREAD_LOCAL_ACCESS record_api_supportability_metric(:add_custom_attributes) if params.is_a? Hash @@ -644,7 +644,7 @@ def add_custom_span_attributes params # # @api public # - def set_transaction_name(name, options={}) + def set_transaction_name(name, options = {}) record_api_supportability_metric(:set_transaction_name) Transaction.set_overriding_transaction_name(name, options[:category]) end @@ -654,7 +654,7 @@ def set_transaction_name(name, options={}) # # @api public # - def get_transaction_name #THREAD_LOCAL_ACCESS + def get_transaction_name # THREAD_LOCAL_ACCESS record_api_supportability_metric(:get_transaction_name) txn = Transaction.tl_current @@ -686,13 +686,13 @@ def with_database_metric_name(model, method = nil, product = nil, &block) # Subscribe to events of +event_type+, calling the given +handler+ # when one is sent. def subscribe(event_type, &handler) - agent.events.subscribe( event_type, &handler ) + agent.events.subscribe(event_type, &handler) end # Fire an event of the specified +event_type+, passing it an the given +args+ # to any registered handlers. def notify(event_type, *args) - agent.events.notify( event_type, *args ) + agent.events.notify(event_type, *args) rescue NewRelic::Agent.logger.debug "Ignoring exception during %p event notification" % [event_type] end @@ -743,7 +743,7 @@ def linking_metadata metadata end - #@!endgroup + # @!endgroup # @!group Manual browser monitoring configuration @@ -763,7 +763,7 @@ def linking_metadata # # @api public # - def browser_timing_header(nonce=nil) + def browser_timing_header(nonce = nil) record_api_supportability_metric(:browser_timing_header) return "" unless agent diff --git a/lib/new_relic/agent/adaptive_sampler.rb b/lib/new_relic/agent/adaptive_sampler.rb index 8d4b7ae58e..56bab03515 100644 --- a/lib/new_relic/agent/adaptive_sampler.rb +++ b/lib/new_relic/agent/adaptive_sampler.rb @@ -5,7 +5,6 @@ module NewRelic module Agent class AdaptiveSampler - def initialize target_samples = 10, period_duration = 60 @target = target_samples @seen = 0 @@ -41,7 +40,7 @@ def sampled? end def exponential_backoff - @target ** (@target.to_f / @sampled_count) - @target ** 0.5 + @target**(@target.to_f / @sampled_count) - @target**0.5 end def stats @@ -62,7 +61,7 @@ def reset_if_period_expired! return unless @period_start + @period_duration <= now elapsed_periods = Integer((now - @period_start) / @period_duration) - @period_start = @period_start + elapsed_periods * @period_duration + @period_start += elapsed_periods * @period_duration @first_period = false @seen_last = elapsed_periods > 1 ? 0 : @seen diff --git a/lib/new_relic/agent/agent.rb b/lib/new_relic/agent/agent.rb index b773a36446..10290cfce6 100644 --- a/lib/new_relic/agent/agent.rb +++ b/lib/new_relic/agent/agent.rb @@ -37,7 +37,6 @@ module NewRelic module Agent - # The Agent is a singleton that is instantiated when the plugin is # activated. It collects performance data from ruby applications # in realtime as the application runs, and periodically sends that @@ -54,31 +53,31 @@ def initialize @service = NewRelicService.new - @events = EventListener.new - @stats_engine = StatsEngine.new - @transaction_sampler = TransactionSampler.new - @sql_sampler = SqlSampler.new - @agent_command_router = Commands::AgentCommandRouter.new @events - @monitors = Monitors.new @events - @error_collector = ErrorCollector.new @events - @transaction_rules = RulesEngine.new - @harvest_samplers = SamplerCollection.new @events - @monotonic_gc_profiler = VM::MonotonicGCProfiler.new - @javascript_instrumentor = JavascriptInstrumentor.new @events - @adaptive_sampler = AdaptiveSampler.new(Agent.config[:sampling_target], - Agent.config[:sampling_target_period_in_seconds]) - - @harvester = Harvester.new @events + @events = EventListener.new + @stats_engine = StatsEngine.new + @transaction_sampler = TransactionSampler.new + @sql_sampler = SqlSampler.new + @agent_command_router = Commands::AgentCommandRouter.new @events + @monitors = Monitors.new @events + @error_collector = ErrorCollector.new @events + @transaction_rules = RulesEngine.new + @harvest_samplers = SamplerCollection.new @events + @monotonic_gc_profiler = VM::MonotonicGCProfiler.new + @javascript_instrumentor = JavascriptInstrumentor.new @events + @adaptive_sampler = AdaptiveSampler.new(Agent.config[:sampling_target], + Agent.config[:sampling_target_period_in_seconds]) + + @harvester = Harvester.new @events @after_fork_lock = Mutex.new @transaction_event_recorder = TransactionEventRecorder.new @events - @custom_event_aggregator = CustomEventAggregator.new @events - @span_event_aggregator = SpanEventAggregator.new @events + @custom_event_aggregator = CustomEventAggregator.new @events + @span_event_aggregator = SpanEventAggregator.new @events - @connect_state = :pending - @connect_attempts = 0 - @waited_on_connect = nil - @connected_pid = nil + @connect_state = :pending + @connect_attempts = 0 + @waited_on_connect = nil + @connected_pid = nil @wait_on_connect_mutex = Mutex.new @wait_on_connect_condition = ConditionVariable.new @@ -110,7 +109,6 @@ def instance # Holds all the methods defined on NewRelic::Agent::Agent # instances module InstanceMethods - # the statistics engine that holds all the timeslice data attr_reader :stats_engine # the transaction sampler that handles recording transactions @@ -184,7 +182,7 @@ def agent_id=(agent_id) # * :keep_retrying => false if we try to initiate a new # connection, this tells me to only try it once so this method returns # quickly if there is some kind of latency with the server. - def after_fork(options={}) + def after_fork(options = {}) needs_restart = false @after_fork_lock.synchronize do needs_restart = @harvester.needs_restart? @@ -284,7 +282,7 @@ def untraced_graceful_disconnect # Sets a thread local variable as to whether we should or # should not record sql in the current thread. Returns the # previous value, if there is one - def set_record_sql(should_record) #THREAD_LOCAL_ACCESS + def set_record_sql(should_record) # THREAD_LOCAL_ACCESS state = Tracer.state prev = state.record_sql state.record_sql = should_record @@ -295,13 +293,13 @@ def set_record_sql(should_record) #THREAD_LOCAL_ACCESS # thread. This uses a stack which allows us to disable tracing # children of a transaction without affecting the tracing of # the whole transaction - def push_trace_execution_flag(should_trace=false) #THREAD_LOCAL_ACCESS + def push_trace_execution_flag(should_trace = false) # THREAD_LOCAL_ACCESS Tracer.state.push_traced(should_trace) end # Pop the current trace execution status. Restore trace execution status # to what it was before we pushed the current flag. - def pop_trace_execution_flag #THREAD_LOCAL_ACCESS + def pop_trace_execution_flag # THREAD_LOCAL_ACCESS Tracer.state.pop_traced end @@ -492,7 +490,7 @@ def check_config_and_start_agent # after_fork call restarting the thread in deferred dispatchers. # # Treatment of @started and env report is important to get right. - def setup_and_start_agent(options={}) + def setup_and_start_agent(options = {}) @started = true @harvester.mark_started @@ -755,7 +753,7 @@ def disconnected? # Don't connect if we're already connected, or if we tried to connect # and were rejected with prejudice because of a license issue, unless # we're forced to by force_reconnect. - def should_connect?(force=false) + def should_connect?(force = false) force || (!connected? && !disconnected?) end @@ -788,7 +786,8 @@ def log_error(error) def handle_license_error(error) ::NewRelic::Agent.logger.error( \ error.message, \ - "Visit NewRelic.com to obtain a valid license key, or to upgrade your account.") + "Visit NewRelic.com to obtain a valid license key, or to upgrade your account." + ) disconnect end @@ -881,20 +880,19 @@ def wait_on_connect(timeout) raise WaitOnConnectTimeout, "Agent was unable to connect in #{timeout} seconds." end end - end include Connect def container_for_endpoint(endpoint) case endpoint - when :metric_data then @stats_engine + when :metric_data then @stats_engine when :transaction_sample_data then @transaction_sampler - when :error_data then @error_collector.error_trace_aggregator - when :error_event_data then @error_collector.error_event_aggregator - when :analytic_event_data then transaction_event_aggregator - when :custom_event_data then @custom_event_aggregator - when :span_event_data then span_event_aggregator - when :sql_trace_data then @sql_sampler + when :error_data then @error_collector.error_trace_aggregator + when :error_event_data then @error_collector.error_event_aggregator + when :analytic_event_data then transaction_event_aggregator + when :custom_event_data then @custom_event_aggregator + when :span_event_data then span_event_aggregator + when :sql_trace_data then @sql_sampler end end @@ -931,7 +929,7 @@ def merge_data_for_endpoint(endpoint, data) # This is useful primarily when re-establishing a new connection after # forking off from a parent process. # - def connect(options={}) + def connect(options = {}) defaults = { :keep_retrying => Agent.config[:keep_retrying], :force_reconnect => Agent.config[:force_reconnect] @@ -1067,7 +1065,7 @@ def harvest_and_send_errors def harvest_and_send_analytic_event_data harvest_and_send_from_container(transaction_event_aggregator, :analytic_event_data) - harvest_and_send_from_container(synthetics_event_aggregator, :analytic_event_data) + harvest_and_send_from_container(synthetics_event_aggregator, :analytic_event_data) end def harvest_and_send_custom_event_data diff --git a/lib/new_relic/agent/agent_logger.rb b/lib/new_relic/agent/agent_logger.rb index 5357572b26..c16719be25 100644 --- a/lib/new_relic/agent/agent_logger.rb +++ b/lib/new_relic/agent/agent_logger.rb @@ -12,7 +12,7 @@ module Agent class AgentLogger include LogOnce - def initialize(root = "", override_logger=nil) + def initialize(root = "", override_logger = nil) @already_logged_lock = Mutex.new clear_already_logged create_log(root, override_logger) @@ -50,8 +50,8 @@ def is_startup_logger? # the log level that the backtrace is logged at. If you just want the # default behavior of backtraces logged at debug, use one of the methods # above and pass an Exception as one of the args. - def log_exception(level, e, backtrace_level=level) - @log.send(level, "%p: %s" % [ e.class, e.message ]) + def log_exception(level, e, backtrace_level = level) + @log.send(level, "%p: %s" % [e.class, e.message]) @log.send(backtrace_level) do backtrace = backtrace_from_exception(e) if backtrace @@ -136,8 +136,8 @@ def wants_stdout? end def find_or_create_file_path(path_setting, root) - for abs_path in [ File.expand_path(path_setting), - File.expand_path(File.join(root, path_setting)) ] do + for abs_path in [File.expand_path(path_setting), + File.expand_path(File.join(root, path_setting))] do if File.directory?(abs_path) || (Dir.mkdir(abs_path) rescue nil) return abs_path[%r{^(.*?)/?$}] end @@ -151,10 +151,10 @@ def set_log_level! LOG_LEVELS = { "debug" => ::Logger::DEBUG, - "info" => ::Logger::INFO, - "warn" => ::Logger::WARN, + "info" => ::Logger::INFO, + "warn" => ::Logger::WARN, "error" => ::Logger::ERROR, - "fatal" => ::Logger::FATAL, + "fatal" => ::Logger::FATAL } def self.log_level_for(level) @@ -176,7 +176,6 @@ def gather_startup_logs def self.format_fatal_error message "** [NewRelic] FATAL : #{message}\n" end - end # In an effort to not lose messages during startup, we trap them in memory diff --git a/lib/new_relic/agent/attribute_filter.rb b/lib/new_relic/agent/attribute_filter.rb index 718c574ddf..59a58b060d 100644 --- a/lib/new_relic/agent/attribute_filter.rb +++ b/lib/new_relic/agent/attribute_filter.rb @@ -64,25 +64,25 @@ module Agent class AttributeFilter DST_NONE = 0x0 - DST_TRANSACTION_EVENTS = 1 << 0 - DST_TRANSACTION_TRACER = 1 << 1 - DST_ERROR_COLLECTOR = 1 << 2 - DST_BROWSER_MONITORING = 1 << 3 - DST_SPAN_EVENTS = 1 << 4 + DST_TRANSACTION_EVENTS = 1 << 0 + DST_TRANSACTION_TRACER = 1 << 1 + DST_ERROR_COLLECTOR = 1 << 2 + DST_BROWSER_MONITORING = 1 << 3 + DST_SPAN_EVENTS = 1 << 4 DST_TRANSACTION_SEGMENTS = 1 << 5 - DST_ALL = 0x3f + DST_ALL = 0x3f attr_reader :rules def initialize(config) @enabled_destinations = DST_NONE - @enabled_destinations |= DST_TRANSACTION_TRACER if config[:'transaction_tracer.attributes.enabled'] - @enabled_destinations |= DST_TRANSACTION_EVENTS if config[:'transaction_events.attributes.enabled'] - @enabled_destinations |= DST_ERROR_COLLECTOR if config[:'error_collector.attributes.enabled'] - @enabled_destinations |= DST_BROWSER_MONITORING if config[:'browser_monitoring.attributes.enabled'] - @enabled_destinations |= DST_SPAN_EVENTS if config[:'span_events.attributes.enabled'] + @enabled_destinations |= DST_TRANSACTION_TRACER if config[:'transaction_tracer.attributes.enabled'] + @enabled_destinations |= DST_TRANSACTION_EVENTS if config[:'transaction_events.attributes.enabled'] + @enabled_destinations |= DST_ERROR_COLLECTOR if config[:'error_collector.attributes.enabled'] + @enabled_destinations |= DST_BROWSER_MONITORING if config[:'browser_monitoring.attributes.enabled'] + @enabled_destinations |= DST_SPAN_EVENTS if config[:'span_events.attributes.enabled'] @enabled_destinations |= DST_TRANSACTION_SEGMENTS if config[:'transaction_segments.attributes.enabled'] @enabled_destinations = DST_NONE unless config[:'attributes.enabled'] @@ -90,26 +90,26 @@ def initialize(config) @rules = [] build_rule(config[:'attributes.exclude'], DST_ALL, false) - build_rule(config[:'transaction_tracer.attributes.exclude'], DST_TRANSACTION_TRACER, false) - build_rule(config[:'transaction_events.attributes.exclude'], DST_TRANSACTION_EVENTS, false) - build_rule(config[:'error_collector.attributes.exclude'], DST_ERROR_COLLECTOR, false) - build_rule(config[:'browser_monitoring.attributes.exclude'], DST_BROWSER_MONITORING, false) - build_rule(config[:'span_events.attributes.exclude'], DST_SPAN_EVENTS, false) + build_rule(config[:'transaction_tracer.attributes.exclude'], DST_TRANSACTION_TRACER, false) + build_rule(config[:'transaction_events.attributes.exclude'], DST_TRANSACTION_EVENTS, false) + build_rule(config[:'error_collector.attributes.exclude'], DST_ERROR_COLLECTOR, false) + build_rule(config[:'browser_monitoring.attributes.exclude'], DST_BROWSER_MONITORING, false) + build_rule(config[:'span_events.attributes.exclude'], DST_SPAN_EVENTS, false) build_rule(config[:'transaction_segments.attributes.exclude'], DST_TRANSACTION_SEGMENTS, false) build_rule(['request.parameters.*'], include_destinations_for_capture_params(config[:capture_params]), true) - build_rule(['job.resque.args.*'], include_destinations_for_capture_params(config[:'resque.capture_params']), true) - build_rule(['job.sidekiq.args.*'], include_destinations_for_capture_params(config[:'sidekiq.capture_params']), true) + build_rule(['job.resque.args.*'], include_destinations_for_capture_params(config[:'resque.capture_params']), true) + build_rule(['job.sidekiq.args.*'], include_destinations_for_capture_params(config[:'sidekiq.capture_params']), true) build_rule(['host', 'port_path_or_id'], DST_TRANSACTION_SEGMENTS, config[:'datastore_tracer.instance_reporting.enabled']) - build_rule(['database_name'], DST_TRANSACTION_SEGMENTS, config[:'datastore_tracer.database_name_reporting.enabled']) + build_rule(['database_name'], DST_TRANSACTION_SEGMENTS, config[:'datastore_tracer.database_name_reporting.enabled']) build_rule(config[:'attributes.include'], DST_ALL, true) - build_rule(config[:'transaction_tracer.attributes.include'], DST_TRANSACTION_TRACER, true) - build_rule(config[:'transaction_events.attributes.include'], DST_TRANSACTION_EVENTS, true) - build_rule(config[:'error_collector.attributes.include'], DST_ERROR_COLLECTOR, true) - build_rule(config[:'browser_monitoring.attributes.include'], DST_BROWSER_MONITORING, true) - build_rule(config[:'span_events.attributes.include'], DST_SPAN_EVENTS, true) + build_rule(config[:'transaction_tracer.attributes.include'], DST_TRANSACTION_TRACER, true) + build_rule(config[:'transaction_events.attributes.include'], DST_TRANSACTION_EVENTS, true) + build_rule(config[:'error_collector.attributes.include'], DST_ERROR_COLLECTOR, true) + build_rule(config[:'browser_monitoring.attributes.include'], DST_BROWSER_MONITORING, true) + build_rule(config[:'span_events.attributes.include'], DST_SPAN_EVENTS, true) build_rule(config[:'transaction_segments.attributes.include'], DST_TRANSACTION_SEGMENTS, true) build_uri_rule(config[:'attributes.exclude']) @@ -165,7 +165,7 @@ def build_rule(attribute_names, destinations, is_include) end def build_uri_rule(excluded_attributes) - uri_aliases = %w(uri url request_uri request.uri http.url) + uri_aliases = %w[uri url request_uri request.uri http.url] if (excluded_attributes & uri_aliases).size > 0 build_rule(uri_aliases - excluded_attributes, DST_ALL, false) @@ -175,7 +175,7 @@ def build_uri_rule(excluded_attributes) def apply(attribute_name, default_destinations) return DST_NONE if @enabled_destinations == DST_NONE - destinations = default_destinations + destinations = default_destinations attribute_name = attribute_name.to_s @rules.each do |rule| @@ -225,8 +225,8 @@ def high_security? def cache_prefix_denylist @prefix_denylist = {} @prefix_denylist[:'request.parameters'] = true unless might_allow_prefix_uncached?(:'request.parameters') - @prefix_denylist[:'job.sidekiq.args'] = true unless might_allow_prefix_uncached?(:'job.sidekiq.args') - @prefix_denylist[:'job.resque.args'] = true unless might_allow_prefix_uncached?(:'job.resque.args') + @prefix_denylist[:'job.sidekiq.args'] = true unless might_allow_prefix_uncached?(:'job.sidekiq.args') + @prefix_denylist[:'job.resque.args'] = true unless might_allow_prefix_uncached?(:'job.resque.args') end # Note that the given prefix *must* be a Symbol @@ -257,9 +257,9 @@ class AttributeFilterRule def initialize(attribute_name, destinations, is_include) @attribute_name = attribute_name.sub(/\*$/, "") - @wildcard = attribute_name.end_with?("*") - @is_include = is_include - @destinations = is_include ? destinations : ~destinations + @wildcard = attribute_name.end_with?("*") + @is_include = is_include + @destinations = is_include ? destinations : ~destinations end # Rules are sorted from least specific to most specific diff --git a/lib/new_relic/agent/attributes.rb b/lib/new_relic/agent/attributes.rb index 219f81d5cb..25a8747439 100644 --- a/lib/new_relic/agent/attributes.rb +++ b/lib/new_relic/agent/attributes.rb @@ -7,7 +7,7 @@ module NewRelic module Agent class Attributes - KEY_LIMIT = 255 + KEY_LIMIT = 255 VALUE_LIMIT = 255 COUNT_LIMIT = 64 @@ -73,7 +73,7 @@ def agent_attributes_for(destination) def intrinsic_attributes_for(destination) if destination == NewRelic::Agent::AttributeFilter::DST_TRANSACTION_TRACER || - destination == NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR + destination == NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR @intrinsic_attributes else NewRelic::EMPTY_HASH diff --git a/lib/new_relic/agent/autostart.rb b/lib/new_relic/agent/autostart.rb index 76b3b60b83..952275e2ab 100644 --- a/lib/new_relic/agent/autostart.rb +++ b/lib/new_relic/agent/autostart.rb @@ -18,13 +18,12 @@ module Agent module Autostart extend self - # The constants, executables (i.e. $0) and rake tasks used can be # configured with the config keys 'autostart.denylisted_constants', # 'autostart.denylisted_executables' and # 'autostart.denylisted_rake_tasks' def agent_should_start? - !denylisted_constants? && + !denylisted_constants? && !denylisted_executables? && !in_denylisted_rake_task? end @@ -57,11 +56,11 @@ def denylisted?(value, &block) def in_denylisted_rake_task? tasks = begin - ::Rake.application.top_level_tasks - rescue => e - ::NewRelic::Agent.logger.debug("Not in Rake environment so skipping denylisted_rake_tasks check: #{e}") - [] - end + ::Rake.application.top_level_tasks + rescue => e + ::NewRelic::Agent.logger.debug("Not in Rake environment so skipping denylisted_rake_tasks check: #{e}") + [] + end !(tasks & ::NewRelic::Agent.config[:'autostart.denylisted_rake_tasks'].split(/\s*,\s*/)).empty? end end diff --git a/lib/new_relic/agent/commands/agent_command.rb b/lib/new_relic/agent/commands/agent_command.rb index 41a24ed05f..865abae92e 100644 --- a/lib/new_relic/agent/commands/agent_command.rb +++ b/lib/new_relic/agent/commands/agent_command.rb @@ -9,8 +9,8 @@ class AgentCommand attr_reader :id, :name, :arguments def initialize(raw_collector_command) - @id = raw_collector_command[0] - @name = raw_collector_command[1]["name"] + @id = raw_collector_command[0] + @name = raw_collector_command[1]["name"] @arguments = raw_collector_command[1]["arguments"] end end diff --git a/lib/new_relic/agent/commands/agent_command_router.rb b/lib/new_relic/agent/commands/agent_command_router.rb index 928ab3b206..ff3be03ae8 100644 --- a/lib/new_relic/agent/commands/agent_command_router.rb +++ b/lib/new_relic/agent/commands/agent_command_router.rb @@ -19,15 +19,15 @@ class AgentCommandRouter attr_accessor :thread_profiler_session, :backtrace_service - def initialize(event_listener=nil) - @handlers = Hash.new { |*| Proc.new { |cmd| self.unrecognized_agent_command(cmd) } } + def initialize(event_listener = nil) + @handlers = Hash.new { |*| Proc.new { |cmd| self.unrecognized_agent_command(cmd) } } @backtrace_service = Threading::BacktraceService.new(event_listener) @thread_profiler_session = ThreadProfilerSession.new(@backtrace_service) @handlers['start_profiler'] = Proc.new { |cmd| thread_profiler_session.handle_start_command(cmd) } - @handlers['stop_profiler'] = Proc.new { |cmd| thread_profiler_session.handle_stop_command(cmd) } + @handlers['stop_profiler'] = Proc.new { |cmd| thread_profiler_session.handle_stop_command(cmd) } if event_listener event_listener.subscribe(:before_shutdown, &method(:on_before_shutdown)) @@ -63,6 +63,7 @@ def harvest! # Same with reset! - we don't support asynchronous cancellation of a # running thread profile currently. def merge!(*args); end + def reset!; end def harvest_from_thread_profiler_session @@ -86,7 +87,7 @@ def log_profiles(profiles) def get_agent_commands commands = new_relic_service.get_agent_commands NewRelic::Agent.logger.debug "Received get_agent_commands = #{commands.inspect}" - commands.map {|collector_command| AgentCommand.new(collector_command)} + commands.map { |collector_command| AgentCommand.new(collector_command) } end def invoke_commands(agent_commands) @@ -120,7 +121,7 @@ def success end def error(err) - { ERROR_KEY => err.message } + {ERROR_KEY => err.message} end def call_handler_for(agent_command) diff --git a/lib/new_relic/agent/commands/thread_profiler_session.rb b/lib/new_relic/agent/commands/thread_profiler_session.rb index 995a70f93f..34cdfb2eb6 100644 --- a/lib/new_relic/agent/commands/thread_profiler_session.rb +++ b/lib/new_relic/agent/commands/thread_profiler_session.rb @@ -9,9 +9,7 @@ module NewRelic module Agent module Commands - class ThreadProfilerSession - def initialize(backtrace_service) @backtrace_service = backtrace_service @started_at = nil @@ -106,7 +104,6 @@ def raise_already_started_error msg = "Profile already in progress. Ignoring agent command to start another." raise_command_error(msg) end - end end end diff --git a/lib/new_relic/agent/configuration/default_source.rb b/lib/new_relic/agent/configuration/default_source.rb index b256b1321a..aa5de4dbbe 100644 --- a/lib/new_relic/agent/configuration/default_source.rb +++ b/lib/new_relic/agent/configuration/default_source.rb @@ -7,7 +7,6 @@ module NewRelic module Agent module Configuration - # Helper since default Procs are evaluated in the context of this module def self.value_of(key) Proc.new do @@ -27,7 +26,7 @@ def self.value_of(key) # - if user set prepend to `false` then we use method_alias chaining # - auto, when returned means, try to use prepend unless conflicting gems discovered # - def self.instrumentation_value_of(disable_key, prepend_key=nil) + def self.instrumentation_value_of(disable_key, prepend_key = nil) Proc.new do if NewRelic::Agent.config[disable_key] "disabled" @@ -78,9 +77,9 @@ def self.transform_for(key) def self.config_search_paths Proc.new { paths = [ - File.join("config","newrelic.yml"), + File.join("config", "newrelic.yml"), File.join("newrelic.yml"), - File.join("config","newrelic.yml.erb"), + File.join("config", "newrelic.yml.erb"), File.join("newrelic.yml.erb") ] @@ -144,8 +143,8 @@ def self.framework def self.agent_enabled Proc.new { NewRelic::Agent.config[:enabled] && - (NewRelic::Agent.config[:test_mode] || NewRelic::Agent.config[:monitor_mode]) && - NewRelic::Agent::Autostart.agent_should_start? + (NewRelic::Agent.config[:test_mode] || NewRelic::Agent.config[:monitor_mode]) && + NewRelic::Agent::Autostart.agent_should_start? } end @@ -154,7 +153,7 @@ def self.agent_enabled def self.audit_log_path Proc.new { log_file_path = NewRelic::Agent.config[:log_file_path] - wants_stdout = (log_file_path.upcase == 'STDOUT') + wants_stdout = (log_file_path.upcase == 'STDOUT') audit_log_dir = wants_stdout ? DEFAULT_LOG_DIR : log_file_path File.join(audit_log_dir, 'newrelic_audit.log') @@ -177,7 +176,7 @@ def self.thread_profiler_enabled # set. Once JS errors are GA, browser_monitoring.loader can stop # being dynamic. def self.browser_monitoring_loader - Proc.new { NewRelic::Agent.config[:js_errors_beta] ? "full" : "rum"} + Proc.new { NewRelic::Agent.config[:js_errors_beta] ? "full" : "rum" } end def self.transaction_tracer_transaction_threshold @@ -780,8 +779,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :deprecated => true, :type => Boolean, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.delayed_job', 'If `true`, disables [Delayed::Job instrumentation](/docs/agents/ruby-agent/background-jobs/delayedjob).' - ) + :description => deprecated_description(:'instrumentation.delayed_job', 'If `true`, disables [Delayed::Job instrumentation](/docs/agents/ruby-agent/background-jobs/delayedjob).') }, :disable_sinatra => { :default => false, @@ -789,7 +787,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => Boolean, :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.sinatra', 'If `true` , disables [Sinatra instrumentation](/docs/agents/ruby-agent/frameworks/sinatra-support).' ) + :description => deprecated_description(:'instrumentation.sinatra', 'If `true` , disables [Sinatra instrumentation](/docs/agents/ruby-agent/frameworks/sinatra-support).') }, :disable_sinatra_auto_middleware => { :default => false, @@ -840,8 +838,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :allowed_from_server => false, :deprecated => true, :description => deprecated_description(:'instrumentation.net_http', - 'If `true`, uses `Module#prepend` rather than alias_method for Net::HTTP instrumentation.' - ) + 'If `true`, uses `Module#prepend` rather than alias_method for Net::HTTP instrumentation.') }, :'instrumentation.net_http' => { :default => instrumentation_value_of(:disable_net_http, :prepend_net_instrumentation), @@ -940,40 +937,40 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => "Controls auto-instrumentation of Sinatra at start up. May be one of [auto|prepend|chain|disabled]." }, :'instrumentation.rack' => { - :default => instrumentation_value_of(:disable_rack), - :public => true, - :type => String, + :default => instrumentation_value_of(:disable_rack), + :public => true, + :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Rack. When enabled, the agent hooks into the " \ + :description => "Controls auto-instrumentation of Rack. When enabled, the agent hooks into the " \ "`to_app` method in Rack::Builder to find gems to instrument during " \ "application startup. May be one of [auto|prepend|chain|disabled]." }, :'instrumentation.rack_urlmap' => { - :default => instrumentation_value_of(:disable_rack_urlmap), - :public => true, - :type => String, + :default => instrumentation_value_of(:disable_rack_urlmap), + :public => true, + :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => 'Controls auto-instrumentation of Rack::URLMap at start up. May be one of [auto|prepend|chain|disabled].' + :description => 'Controls auto-instrumentation of Rack::URLMap at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.puma_rack' => { - :default => instrumentation_value_of(:disable_puma_rack), # TODO: change to value_of(:'instrumentation.rack') when we remove :disable_puma_rack in 8.0) - :public => true, - :type => String, + :default => instrumentation_value_of(:disable_puma_rack), # TODO: change to value_of(:'instrumentation.rack') when we remove :disable_puma_rack in 8.0) + :public => true, + :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Puma::Rack. When enabled, the agent hooks into the " \ + :description => "Controls auto-instrumentation of Puma::Rack. When enabled, the agent hooks into the " \ "`to_app` method in Puma::Rack::Builder to find gems to instrument during " \ "application startup. May be one of [auto|prepend|chain|disabled]." }, :'instrumentation.puma_rack_urlmap' => { - :default => instrumentation_value_of(:disable_puma_rack_urlmap), # TODO: change to value_of(:'instrumentation.rack_urlmap') when we remove :disable_puma_rack_urlmap in 8.0) - :public => true, - :type => String, + :default => instrumentation_value_of(:disable_puma_rack_urlmap), # TODO: change to value_of(:'instrumentation.rack_urlmap') when we remove :disable_puma_rack_urlmap in 8.0) + :public => true, + :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => 'Controls auto-instrumentation of Puma::Rack::URLMap at start up. May be one of [auto|prepend|chain|disabled].' + :description => 'Controls auto-instrumentation of Puma::Rack::URLMap at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.memcached' => { :default => instrumentation_value_of(:disable_memcached), @@ -981,7 +978,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => 'Controls auto-instrumentation of memcached gem for Memcache at start up. May be one of [auto|prepend|chain|disabled].' + :description => 'Controls auto-instrumentation of memcached gem for Memcache at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.memcache_client' => { :default => instrumentation_value_of(:disable_memcache_client), @@ -989,7 +986,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => 'Controls auto-instrumentation of memcache-client gem for Memcache at start up. May be one of [auto|prepend|chain|disabled].' + :description => 'Controls auto-instrumentation of memcache-client gem for Memcache at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.memcache' => { :default => instrumentation_value_of(:disable_dalli), @@ -997,7 +994,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => 'Controls auto-instrumentation of dalli gem for Memcache at start up. May be one of [auto|prepend|chain|disabled].' + :description => 'Controls auto-instrumentation of dalli gem for Memcache at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.logger' => { :default => "auto", @@ -1214,36 +1211,36 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => 'Use [`disable_sequel_instrumentation`](#disable_sequel_instrumentation) instead.' }, :disable_mongo => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :allowed_from_server => false, :dynamic_name => true, - :deprecated => true, - :description => deprecated_description(:'instrumentation.mongo', 'If `true`, the agent won\'t install [instrumentation for the Mongo gem](/docs/agents/ruby-agent/frameworks/mongo-instrumentation).') + :deprecated => true, + :description => deprecated_description(:'instrumentation.mongo', 'If `true`, the agent won\'t install [instrumentation for the Mongo gem](/docs/agents/ruby-agent/frameworks/mongo-instrumentation).') }, :disable_redis => { - :default => false, - :public => true, - :type => Boolean, - :deprecated => true, + :default => false, + :public => true, + :type => Boolean, + :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.redis', 'If `true`, the agent won\'t install [instrumentation for Redis](/docs/agents/ruby-agent/frameworks/redis-instrumentation).') + :description => deprecated_description(:'instrumentation.redis', 'If `true`, the agent won\'t install [instrumentation for Redis](/docs/agents/ruby-agent/frameworks/redis-instrumentation).') }, :disable_redis_instrumentation => { - :default => false, - :public => false, - :type => Boolean, - :deprecated => true, + :default => false, + :public => false, + :type => Boolean, + :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.redis', 'Disables installation of Redis instrumentation. Standard key to use is disable_redis.') + :description => deprecated_description(:'instrumentation.redis', 'Disables installation of Redis instrumentation. Standard key to use is disable_redis.') }, :'message_tracer.segment_parameters.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => true, - :description => 'If `true`, the agent will collect metadata about messages and attach them as segment parameters.' + :description => 'If `true`, the agent will collect metadata about messages and attach them as segment parameters.' }, :'slow_sql.enabled' => { :default => value_of(:'transaction_tracer.enabled'), @@ -1313,7 +1310,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :default => 'ActionController::RoutingError,Sinatra::NotFound', :public => true, :type => String, - :deprecated => true, + :deprecated => true, :allowed_from_server => true, :dynamic_name => true, :description => 'Use `error_collector.ignore_classes` instead. Specify a comma-delimited list of error classes that the agent should ignore.' @@ -1595,71 +1592,71 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => 'Backports the faster ActiveRecord connection lookup introduced in Rails 6, which improves agent performance when instrumenting ActiveRecord. Note that this setting may not be compatible with other gems that patch ActiveRecord.' }, :disable_vm_sampler => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :description => 'If `true`, the agent won\'t [sample performance measurements from the Ruby VM](/docs/agents/ruby-agent/features/ruby-vm-measurements).' + :description => 'If `true`, the agent won\'t [sample performance measurements from the Ruby VM](/docs/agents/ruby-agent/features/ruby-vm-measurements).' }, :disable_memory_sampler => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :description => 'If `true`, the agent won\'t sample the memory usage of the host process.' + :description => 'If `true`, the agent won\'t sample the memory usage of the host process.' }, :disable_cpu_sampler => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :description => 'If `true`, the agent won\'t sample the CPU usage of the host process.' + :description => 'If `true`, the agent won\'t sample the CPU usage of the host process.' }, :disable_delayed_job_sampler => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :description => 'If `true`, the agent won\'t measure the depth of Delayed Job queues.' + :description => 'If `true`, the agent won\'t measure the depth of Delayed Job queues.' }, :disable_active_record_notifications => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :description => 'If `true`, disables instrumentation for ActiveRecord 4, 5, and 6.' + :description => 'If `true`, disables instrumentation for ActiveRecord 4, 5, and 6.' }, :disable_bunny => { - :default => false, - :public => true, - :type => Boolean, - :deprecated => true, + :default => false, + :public => true, + :type => Boolean, + :deprecated => true, :dynamic_name => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.bunny', 'If `true`, disables instrumentation for the bunny gem.') + :description => deprecated_description(:'instrumentation.bunny', 'If `true`, disables instrumentation for the bunny gem.') }, :disable_curb => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :deprecated => true, :dynamic_name => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.curb', 'If `true`, disables instrumentation for the curb gem.' ) + :description => deprecated_description(:'instrumentation.curb', 'If `true`, disables instrumentation for the curb gem.') }, :disable_excon => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, - :deprecated => true, + :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.excon', 'If `true`, disables instrumentation for the excon gem.') + :description => deprecated_description(:'instrumentation.excon', 'If `true`, disables instrumentation for the excon gem.') }, :'instrumentation.excon' => { :default => instrumentation_value_of(:disable_excon), @@ -1670,200 +1667,197 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => "Controls auto-instrumentation of Excon at start up. May be one of [enabled|disabled]." }, :disable_httpclient => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, - :deprecated => true, + :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.httpclient', 'If `true`, disables instrumentation for the httpclient gem.') + :description => deprecated_description(:'instrumentation.httpclient', 'If `true`, disables instrumentation for the httpclient gem.') }, :disable_net_http => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.net_http', - 'If `true`, disables instrumentation for Net::HTTP.' - ) + :deprecated => true, + :description => deprecated_description(:'instrumentation.net_http', + 'If `true`, disables instrumentation for Net::HTTP.') }, :disable_rack => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.rack', 'If `true`, prevents the agent from hooking into the `to_app` method in Rack::Builder to find gems to instrument during application startup.') + :deprecated => true, + :description => deprecated_description(:'instrumentation.rack', 'If `true`, prevents the agent from hooking into the `to_app` method in Rack::Builder to find gems to instrument during application startup.') }, :disable_rack_urlmap => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.rack_urlmap', 'If `true`, prevents the agent from hooking into Rack::URLMap to install middleware tracing.') + :deprecated => true, + :description => deprecated_description(:'instrumentation.rack_urlmap', 'If `true`, prevents the agent from hooking into Rack::URLMap to install middleware tracing.') }, :disable_puma_rack => { - :default => value_of(:disable_rack), - :public => true, - :type => Boolean, + :default => value_of(:disable_rack), + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.puma_rack', 'If `true`, prevents the agent from hooking into the `to_app` method in Puma::Rack::Builder to find gems to instrument during application startup.') + :deprecated => true, + :description => deprecated_description(:'instrumentation.puma_rack', 'If `true`, prevents the agent from hooking into the `to_app` method in Puma::Rack::Builder to find gems to instrument during application startup.') }, :disable_puma_rack_urlmap => { - :default => value_of(:disable_rack_urlmap), - :public => true, - :type => Boolean, + :default => value_of(:disable_rack_urlmap), + :public => true, + :type => Boolean, :dynamic_name => true, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.puma_rack_urlmap', 'If `true`, prevents the agent from hooking into Puma::Rack::URLMap to install middleware tracing.') + :deprecated => true, + :description => deprecated_description(:'instrumentation.puma_rack_urlmap', 'If `true`, prevents the agent from hooking into Puma::Rack::URLMap to install middleware tracing.') }, :disable_typhoeus => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, - :deprecated => true, + :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.typhoeus', 'If `true`, the agent won\'t install instrumentation for the typhoeus gem.' ) + :description => deprecated_description(:'instrumentation.typhoeus', 'If `true`, the agent won\'t install instrumentation for the typhoeus gem.') }, :disable_httprb => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :dynamic_name => true, - :deprecated => true, + :deprecated => true, :allowed_from_server => false, - :description => deprecated_description(:'instrumentation.httprb', 'If `true`, the agent won\'t install instrumentation for the http.rb gem.' ) + :description => deprecated_description(:'instrumentation.httprb', 'If `true`, the agent won\'t install instrumentation for the http.rb gem.') }, :disable_middleware_instrumentation => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :allowed_from_server => false, - :description => 'If `true`, the agent won\'t wrap third-party middlewares in instrumentation (regardless of whether they are installed via Rack::Builder or Rails).' + :description => 'If `true`, the agent won\'t wrap third-party middlewares in instrumentation (regardless of whether they are installed via Rack::Builder or Rails).' }, :disable_rails_middleware => { - :default => false, - :public => false, - :type => Boolean, + :default => false, + :public => false, + :type => Boolean, :allowed_from_server => false, - :description => 'Internal name for controlling Rails 3+ middleware instrumentation' + :description => 'Internal name for controlling Rails 3+ middleware instrumentation' }, :'heroku.use_dyno_names' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, - :description => 'If `true`, the agent uses Heroku dyno names as the hostname.' + :description => 'If `true`, the agent uses Heroku dyno names as the hostname.' }, :'heroku.dyno_name_prefixes_to_shorten' => { - :default => ['scheduler', 'run'], - :public => true, - :type => Array, + :default => ['scheduler', 'run'], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), - :description => 'Ordinarily the agent reports dyno names with a trailing dot and process ID (for example, worker.3). You can remove this trailing data by specifying the prefixes you want to report without trailing data (for example, worker).' + :transform => DefaultSource.method(:convert_to_list), + :description => 'Ordinarily the agent reports dyno names with a trailing dot and process ID (for example, worker.3). You can remove this trailing data by specifying the prefixes you want to report without trailing data (for example, worker).' }, :'process_host.display_name' => { - :default => Proc.new{ NewRelic::Agent::Hostname.get }, - :public => true, - :type => String, + :default => Proc.new { NewRelic::Agent::Hostname.get }, + :public => true, + :type => String, :allowed_from_server => false, - :description => 'Specify a custom host name for [display in the New Relic UI](/docs/apm/new-relic-apm/maintenance/add-rename-remove-hosts#display_name).' + :description => 'Specify a custom host name for [display in the New Relic UI](/docs/apm/new-relic-apm/maintenance/add-rename-remove-hosts#display_name).' }, :labels => { - :default => '', - :public => true, - :type => String, + :default => '', + :public => true, + :type => String, :allowed_from_server => false, - :description => 'A dictionary of [label names](/docs/data-analysis/user-interface-functions/labels-categories-organize-your-apps-servers) and values that will be applied to the data sent from this agent. May also be expressed as a semicolon-delimited `;` string of colon-separated `:` pairs. For example, `Server:One;Data Center:Primary`.' + :description => 'A dictionary of [label names](/docs/data-analysis/user-interface-functions/labels-categories-organize-your-apps-servers) and values that will be applied to the data sent from this agent. May also be expressed as a semicolon-delimited `;` string of colon-separated `:` pairs. For example, `Server:One;Data Center:Primary`.' }, :aggressive_keepalive => { - :default => true, - :public => false, - :type => Boolean, + :default => true, + :public => false, + :type => Boolean, :allowed_from_server => true, - :description => 'If true, attempt to keep the TCP connection to the collector alive between harvests.' + :description => 'If true, attempt to keep the TCP connection to the collector alive between harvests.' }, :keep_alive_timeout => { - :default => 60, - :public => false, - :type => Integer, + :default => 60, + :public => false, + :type => Integer, :allowed_from_server => true, - :description => 'Timeout for keep alive on TCP connection to collector if supported by Ruby version. Only used in conjunction when aggressive_keepalive is enabled.' + :description => 'Timeout for keep alive on TCP connection to collector if supported by Ruby version. Only used in conjunction when aggressive_keepalive is enabled.' }, :ca_bundle_path => { - :default => nil, - :allow_nil => true, - :public => true, - :type => String, + :default => nil, + :allow_nil => true, + :public => true, + :type => String, :allowed_from_server => false, - :description => "Manual override for the path to your local CA bundle. This CA bundle will be used to validate the SSL certificate presented by New Relic\'s data collection service." + :description => "Manual override for the path to your local CA bundle. This CA bundle will be used to validate the SSL certificate presented by New Relic\'s data collection service." }, :'rules.ignore_url_regexes' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => true, - :transform => DefaultSource.method(:convert_to_regexp_list), - :description => 'Define transactions you want the agent to ignore, by specifying a list of patterns matching the URI you want to ignore.' + :transform => DefaultSource.method(:convert_to_regexp_list), + :description => 'Define transactions you want the agent to ignore, by specifying a list of patterns matching the URI you want to ignore.' }, :'synthetics.traces_limit' => { - :default => 20, - :public => false, - :type => Integer, + :default => 20, + :public => false, + :type => Integer, :allowed_from_server => true, - :description => 'Maximum number of synthetics transaction traces to hold for a given harvest' + :description => 'Maximum number of synthetics transaction traces to hold for a given harvest' }, :'synthetics.events_limit' => { - :default => 200, - :public => false, - :type => Integer, + :default => 200, + :public => false, + :type => Integer, :allowed_from_server => true, - :description => 'Maximum number of synthetics transaction events to hold for a given harvest' + :description => 'Maximum number of synthetics transaction events to hold for a given harvest' }, :'custom_insights_events.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => true, - :description => 'If `true`, the agent captures [New Relic Insights custom events](/docs/insights/new-relic-insights/adding-querying-data/inserting-custom-events-new-relic-apm-agents).' + :description => 'If `true`, the agent captures [New Relic Insights custom events](/docs/insights/new-relic-insights/adding-querying-data/inserting-custom-events-new-relic-apm-agents).' }, :'custom_insights_events.max_samples_stored' => { - :default => 1000, - :public => true, - :type => Integer, + :default => 1000, + :public => true, + :type => Integer, :allowed_from_server => true, - :description => 'Specify a maximum number of custom Insights events to buffer in memory at a time.', + :description => 'Specify a maximum number of custom Insights events to buffer in memory at a time.', :dynamic_name => true }, :disable_grape_instrumentation => { - :default => false, - :public => false, - :type => Boolean, + :default => false, + :public => false, + :type => Boolean, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.grape', - 'If `true`, the agent won\'t install Grape instrumentation.' - ) + :deprecated => true, + :description => deprecated_description(:'instrumentation.grape', + 'If `true`, the agent won\'t install Grape instrumentation.') }, :disable_grape => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :allowed_from_server => false, - :deprecated => true, - :description => deprecated_description(:'instrumentation.grape', - 'If `true`, the agent won\'t install Grape instrumentation.' - ) + :deprecated => true, + :description => deprecated_description(:'instrumentation.grape', + 'If `true`, the agent won\'t install Grape instrumentation.') }, :'instrumentation.grape' => { :default => instrumentation_value_of(:disable_grape_instrumentation), @@ -1874,261 +1868,261 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => "Controls auto-instrumentation of Grape at start up. May be one of [auto|prepend|chain|disabled]." }, :'attributes.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, enables capture of attributes for all destinations.' }, :'transaction_tracer.attributes.enabled' => { - :default => value_of(:'transaction_tracer.capture_attributes'), - :public => true, - :type => Boolean, + :default => value_of(:'transaction_tracer.capture_attributes'), + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent captures attributes from transaction traces.' }, :'transaction_events.attributes.enabled' => { - :default => value_of(:'analytics_events.capture_attributes'), - :public => true, - :type => Boolean, + :default => value_of(:'analytics_events.capture_attributes'), + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent captures attributes from transaction events.' }, :'error_collector.attributes.enabled' => { - :default => value_of(:'error_collector.capture_attributes'), - :public => true, - :type => Boolean, + :default => value_of(:'error_collector.capture_attributes'), + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent captures attributes from error collection.' }, :'browser_monitoring.attributes.enabled' => { - :default => value_of(:'browser_monitoring.capture_attributes'), - :public => true, - :type => Boolean, + :default => value_of(:'browser_monitoring.capture_attributes'), + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent captures attributes from browser monitoring.' }, :'span_events.attributes.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent captures attributes on span events.' }, :'transaction_segments.attributes.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent captures attributes on transaction segments.' }, :'attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from all destinations. Allows `*` as wildcard at end.' }, :'transaction_tracer.attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from transaction traces. Allows `*` as wildcard at end.' }, :'transaction_events.attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from transaction events. Allows `*` as wildcard at end.' }, :'error_collector.attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from error collection. Allows `*` as wildcard at end.' }, :'browser_monitoring.attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from browser monitoring. Allows `*` as wildcard at end.' }, :'span_events.attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from span events. Allows `*` as wildcard at end.' }, :'transaction_segments.attributes.exclude' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to exclude from transaction segments. Allows `*` as wildcard at end.' }, :'attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include in all destinations. Allows `*` as wildcard at end.' }, :'transaction_tracer.attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include in transaction traces. Allows `*` as wildcard at end.' }, :'transaction_events.attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include in transaction events. Allows `*` as wildcard at end.' }, :'error_collector.attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include in error collection. Allows `*` as wildcard at end.' }, :'browser_monitoring.attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include in browser monitoring. Allows `*` as wildcard at end.' }, :'span_events.attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include on span events. Allows `*` as wildcard at end.' }, :'transaction_segments.attributes.include' => { - :default => [], - :public => true, - :type => Array, + :default => [], + :public => true, + :type => Array, :allowed_from_server => false, - :transform => DefaultSource.method(:convert_to_list), + :transform => DefaultSource.method(:convert_to_list), :description => 'Prefix of attributes to include on transaction segments. Allows `*` as wildcard at end.' }, :'custom_attributes.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `false`, custom attributes will not be sent on Insights events.' }, :'utilization.detect_aws' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :dynamic_name => true, :description => 'If `true`, the agent automatically detects that it is running in an AWS environment.' }, :'utilization.detect_azure' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :dynamic_name => true, - :description => 'If `true`, the agent automatically detects that it is running in an Azure environment.' + :description => 'If `true`, the agent automatically detects that it is running in an Azure environment.' }, :'utilization.detect_gcp' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :dynamic_name => true, :description => 'If `true`, the agent automatically detects that it is running in an Google Cloud Platform environment.' }, :'utilization.detect_pcf' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :dynamic_name => true, :description => 'If `true`, the agent automatically detects that it is running in a Pivotal Cloud Foundry environment.' }, :'utilization.detect_docker' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent automatically detects that it is running in Docker.' }, :'utilization.detect_kubernetes' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent automatically detects that it is running in Kubernetes.' }, :'utilization.billing_hostname' => { - :default => nil, - :allow_nil => true, - :public => false, - :type => String, + :default => nil, + :allow_nil => true, + :public => false, + :type => String, :allowed_from_server => false, :description => 'The configured server name by a customer.' }, :'utilization.logical_processors' => { - :default => nil, - :allow_nil => true, - :public => false, - :type => Integer, + :default => nil, + :allow_nil => true, + :public => false, + :type => Integer, :allowed_from_server => false, :description => 'The total number of hyper-threaded execution contexts available.' }, :'utilization.total_ram_mib' => { - :default => nil, - :allow_nil => true, - :public => false, - :type => Integer, + :default => nil, + :allow_nil => true, + :public => false, + :type => Integer, :allowed_from_server => false, :description => 'This value represents the total amount of memory available to the host (not the process), in mebibytes (1024 squared or 1,048,576 bytes).' }, :'datastore_tracer.instance_reporting.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `false`, the agent will not report datastore instance metrics, nor add `host` or `port_path_or_id` parameters to transaction or slow SQL traces.' }, :'datastore_tracer.database_name_reporting.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `false`, the agent will not add `database_name` parameter to transaction or slow sql traces.' }, :'clear_transaction_state_after_fork' => { - :default => false, - :public => true, - :type => Boolean, + :default => false, + :public => true, + :type => Boolean, :allowed_from_server => false, :description => 'If `true`, the agent will clear `Tracer::State` in `Agent.drop_buffered_data`.' }, @@ -2149,9 +2143,9 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => 'The primary id associated with this application.' }, :'distributed_tracing.enabled' => { - :default => true, - :public => true, - :type => Boolean, + :default => true, + :public => true, + :type => Boolean, :allowed_from_server => true, :description => 'Distributed tracing lets you see the path that a request takes through your distributed system. Enabling distributed tracing changes the behavior of some New Relic features, so carefully consult the [transition guide](/docs/transition-guide-distributed-tracing) before you enable this feature.' }, diff --git a/lib/new_relic/agent/configuration/dotted_hash.rb b/lib/new_relic/agent/configuration/dotted_hash.rb index e0e9044c4f..0bc0eb162b 100644 --- a/lib/new_relic/agent/configuration/dotted_hash.rb +++ b/lib/new_relic/agent/configuration/dotted_hash.rb @@ -6,7 +6,7 @@ module NewRelic module Agent module Configuration class DottedHash < ::Hash - def initialize(hash, keep_nesting=false) + def initialize(hash, keep_nesting = false) # Add the hash keys to our collection explicitly so they survive the # dot flattening. This is typical for full config source instances, # but not for uses of DottedHash serializing for transmission. @@ -31,8 +31,9 @@ def self.symbolize(hash) end protected + # turns {'a' => {'b' => 'c'}} into {'a.b' => 'c'} - def dot_flattened(nested_hash, names=[], result={}) + def dot_flattened(nested_hash, names = [], result = {}) nested_hash.each do |key, val| next if val == nil if val.respond_to?(:has_key?) @@ -44,7 +45,6 @@ def dot_flattened(nested_hash, names=[], result={}) result end end - end end end diff --git a/lib/new_relic/agent/configuration/environment_source.rb b/lib/new_relic/agent/configuration/environment_source.rb index 2f2ae3a64e..db87dfec7b 100644 --- a/lib/new_relic/agent/configuration/environment_source.rb +++ b/lib/new_relic/agent/configuration/environment_source.rb @@ -7,9 +7,9 @@ module Agent module Configuration class EnvironmentSource < DottedHash SUPPORTED_PREFIXES = /^new_relic_|^newrelic_/i - SPECIAL_CASE_KEYS = [ + SPECIAL_CASE_KEYS = [ 'NEW_RELIC_ENV', # read by NewRelic::Control::Frameworks::Ruby - 'NEW_RELIC_LOG', # read by set_log_file + 'NEW_RELIC_LOG', # read by set_log_file /^NEW_RELIC_METADATA_/ # read by NewRelic::Agent::Connect::RequestBuilder ] @@ -43,7 +43,7 @@ def set_dotted_alias(original_config_setting) config_setting = original_config_setting.to_s if config_setting.include? '.' - config_alias = config_setting.gsub(/\./,'_').to_sym + config_alias = config_setting.gsub(/\./, '_').to_sym self.alias_map[config_alias] = original_config_setting end end @@ -111,7 +111,6 @@ def convert_environment_key_to_config_key(key) def collect_new_relic_environment_variable_keys ENV.keys.select { |key| key.match(SUPPORTED_PREFIXES) } end - end end end diff --git a/lib/new_relic/agent/configuration/event_harvest_config.rb b/lib/new_relic/agent/configuration/event_harvest_config.rb index 257d968317..d0b747cdde 100644 --- a/lib/new_relic/agent/configuration/event_harvest_config.rb +++ b/lib/new_relic/agent/configuration/event_harvest_config.rb @@ -6,13 +6,12 @@ module NewRelic module Agent module Configuration module EventHarvestConfig - extend self EVENT_HARVEST_CONFIG_KEY_MAPPING = { :analytic_event_data => :'analytics_events.max_samples_stored', :custom_event_data => :'custom_insights_events.max_samples_stored', - :error_event_data => :'error_collector.max_event_samples_stored', + :error_event_data => :'error_collector.max_event_samples_stored' } def from_config(config) @@ -22,8 +21,7 @@ def from_config(config) ).inject({}) do |connect_payload, (connect_payload_key, config_key)| connect_payload[connect_payload_key] = config[config_key] connect_payload - end - } + end} end def to_config_hash(connect_reply) diff --git a/lib/new_relic/agent/configuration/high_security_source.rb b/lib/new_relic/agent/configuration/high_security_source.rb index f88840879f..6d2b73686a 100644 --- a/lib/new_relic/agent/configuration/high_security_source.rb +++ b/lib/new_relic/agent/configuration/high_security_source.rb @@ -10,17 +10,17 @@ module Configuration class HighSecuritySource < DottedHash def initialize(local_settings) super({ - :capture_params => false, - :'resque.capture_params' => false, + :capture_params => false, + :'resque.capture_params' => false, :'sidekiq.capture_params' => false, - :'attributes.include' => [], + :'attributes.include' => [], :'transaction_tracer.record_sql' => record_sql_setting(local_settings, :'transaction_tracer.record_sql'), - :'slow_sql.record_sql' => record_sql_setting(local_settings, :'slow_sql.record_sql'), - :'mongo.obfuscate_queries' => true, + :'slow_sql.record_sql' => record_sql_setting(local_settings, :'slow_sql.record_sql'), + :'mongo.obfuscate_queries' => true, :'transaction_tracer.record_redis_arguments' => false, - :'custom_insights_events.enabled' => false, + :'custom_insights_events.enabled' => false, :'strip_exception_messages.enabled' => true }) end @@ -32,7 +32,7 @@ def initialize(local_settings) SET_TO_OBFUSCATED = [RAW, OBFUSCATED] def record_sql_setting(local_settings, key) - original_value = local_settings[key] + original_value = local_settings[key] result = if SET_TO_OBFUSCATED.include?(original_value) OBFUSCATED else diff --git a/lib/new_relic/agent/configuration/manager.rb b/lib/new_relic/agent/configuration/manager.rb index 9383402793..33a4f28d88 100644 --- a/lib/new_relic/agent/configuration/manager.rb +++ b/lib/new_relic/agent/configuration/manager.rb @@ -31,10 +31,10 @@ def keys def initialize reset_to_defaults - @callbacks = Hash.new {|hash,key| hash[key] = [] } + @callbacks = Hash.new { |hash, key| hash[key] = [] } end - def add_config_for_testing(source, level=0) + def add_config_for_testing(source, level = 0) raise 'Invalid config type for testing' unless [Hash, DottedHash].include?(source.class) invoke_callbacks(:add, source) @configs_for_testing << [source.freeze, level] @@ -45,12 +45,12 @@ def add_config_for_testing(source, level=0) def remove_config_type(sym) source = case sym when :security_policy then @security_policy_source - when :high_security then @high_security_source - when :environment then @environment_source - when :server then @server_source - when :manual then @manual_source - when :yaml then @yaml_source - when :default then @default_source + when :high_security then @high_security_source + when :environment then @environment_source + when :server then @server_source + when :manual then @manual_source + when :yaml then @yaml_source + when :default then @default_source end remove_config(source) @@ -59,14 +59,14 @@ def remove_config_type(sym) def remove_config(source) case source when SecurityPolicySource then @security_policy_source = nil - when HighSecuritySource then @high_security_source = nil - when EnvironmentSource then @environment_source = nil - when ServerSource then @server_source = nil - when ManualSource then @manual_source = nil - when YamlSource then @yaml_source = nil - when DefaultSource then @default_source = nil + when HighSecuritySource then @high_security_source = nil + when EnvironmentSource then @environment_source = nil + when ServerSource then @server_source = nil + when ManualSource then @manual_source = nil + when YamlSource then @yaml_source = nil + when DefaultSource then @default_source = nil else - @configs_for_testing.delete_if {|src,lvl| src == source} + @configs_for_testing.delete_if { |src, lvl| src == source } end reset_cache @@ -82,12 +82,12 @@ def replace_or_add_config(source) case source when SecurityPolicySource then @security_policy_source = source - when HighSecuritySource then @high_security_source = source - when EnvironmentSource then @environment_source = source - when ServerSource then @server_source = source - when ManualSource then @manual_source = source - when YamlSource then @yaml_source = source - when DefaultSource then @default_source = source + when HighSecuritySource then @high_security_source = source + when EnvironmentSource then @environment_source = source + when ServerSource then @server_source = source + when ManualSource then @manual_source = source + when YamlSource then @yaml_source = source + when DefaultSource then @default_source = source else NewRelic::Agent.logger.warn("Invalid config format; config will be ignored: #{source}") end @@ -191,9 +191,9 @@ def finished_configuring? end def flattened - config_stack.reverse.inject({}) do |flat,layer| + config_stack.reverse.inject({}) do |flat, layer| thawed_layer = layer.to_hash.dup - thawed_layer.each do |k,v| + thawed_layer.each do |k, v| begin thawed_layer[k] = instance_eval(&v) if v.respond_to?(:call) rescue => e @@ -207,9 +207,9 @@ def flattened end def apply_mask(hash) - MASK_DEFAULTS. \ - select {|_, proc| proc.call}. \ - each {|key, _| hash.delete(key) } + MASK_DEFAULTS \ + .select { |_, proc| proc.call } \ + .each { |key, _| hash.delete(key) } hash end @@ -228,9 +228,9 @@ def to_collector_hash end MALFORMED_LABELS_WARNING = "Skipping malformed labels configuration" - PARSING_LABELS_FAILURE = "Failure during parsing labels. Ignoring and carrying on with connect." + PARSING_LABELS_FAILURE = "Failure during parsing labels. Ignoring and carrying on with connect." - MAX_LABEL_COUNT = 64 + MAX_LABEL_COUNT = 64 MAX_LABEL_LENGTH = 255 def parsed_labels @@ -252,7 +252,7 @@ def parse_labels_from_string end def break_label_string_into_pairs(labels) - stripped_labels = labels.strip.sub(/^;*/,'').sub(/;*$/,'') + stripped_labels = labels.strip.sub(/^;*/, '').sub(/;*$/, '') stripped_labels.split(';').map do |pair| pair.split(':').map(&:strip) end @@ -268,10 +268,10 @@ def valid_label_pairs?(label_pairs) def valid_label_item?(item) case item - when String then !item.empty? + when String then !item.empty? when Numeric then true - when true then true - when false then true + when true then true + when false then true else false end end @@ -281,7 +281,7 @@ def make_label_hash(pairs, labels = nil) pairs = Array(pairs) unless valid_label_pairs?(pairs) - NewRelic::Agent.logger.warn("#{MALFORMED_LABELS_WARNING}: #{labels||pairs}") + NewRelic::Agent.logger.warn("#{MALFORMED_LABELS_WARNING}: #{labels || pairs}") return [] end @@ -289,13 +289,13 @@ def make_label_hash(pairs, labels = nil) pairs = remove_duplicates(pairs) pairs.map do |key, value| { - 'label_type' => truncate(key), + 'label_type' => truncate(key), 'label_value' => truncate(value.to_s, key) } end end - def truncate(text, key=nil) + def truncate(text, key = nil) if text.length > MAX_LABEL_LENGTH if key msg = "The value for the label '#{key}' is longer than the allowed #{MAX_LABEL_LENGTH} and will be truncated. Value = '#{text}'" @@ -303,7 +303,7 @@ def truncate(text, key=nil) msg = "Label name longer than the allowed #{MAX_LABEL_LENGTH} will be truncated. Name = '#{text}'" end NewRelic::Agent.logger.warn(msg) - text[0..MAX_LABEL_LENGTH-1] + text[0..MAX_LABEL_LENGTH - 1] else text end @@ -331,20 +331,20 @@ def parse_labels_from_dictionary # Generally only useful during initial construction and tests def reset_to_defaults @security_policy_source = nil - @high_security_source = nil - @environment_source = EnvironmentSource.new - @server_source = nil - @manual_source = nil - @yaml_source = nil - @default_source = DefaultSource.new + @high_security_source = nil + @environment_source = EnvironmentSource.new + @server_source = nil + @manual_source = nil + @yaml_source = nil + @default_source = DefaultSource.new - @configs_for_testing = [] + @configs_for_testing = [] reset_cache end def reset_cache - @cache = Hash.new { |hash,key| hash[key] = self.fetch(key) } + @cache = Hash.new { |hash, key| hash[key] = self.fetch(key) } end def log_config(direction, source) @@ -359,13 +359,13 @@ def log_config(direction, source) def delete_all_configs_for_testing @security_policy_source = nil - @high_security_source = nil - @environment_source = nil - @server_source = nil - @manual_source = nil - @yaml_source = nil - @default_source = nil - @configs_for_testing = [] + @high_security_source = nil + @environment_source = nil + @server_source = nil + @manual_source = nil + @yaml_source = nil + @default_source = nil + @configs_for_testing = [] end def num_configs_for_testing @@ -380,12 +380,12 @@ def config_classes_for_testing def config_stack stack = [@security_policy_source, - @high_security_source, - @environment_source, - @server_source, - @manual_source, - @yaml_source, - @default_source] + @high_security_source, + @environment_source, + @server_source, + @manual_source, + @yaml_source, + @default_source] stack.compact! diff --git a/lib/new_relic/agent/configuration/mask_defaults.rb b/lib/new_relic/agent/configuration/mask_defaults.rb index 433b66ed75..24c66b58e6 100644 --- a/lib/new_relic/agent/configuration/mask_defaults.rb +++ b/lib/new_relic/agent/configuration/mask_defaults.rb @@ -6,7 +6,7 @@ module NewRelic module Agent module Configuration MASK_DEFAULTS = { - :'thread_profiler' => Proc.new { !NewRelic::Agent::Threading::BacktraceService.is_supported? }, + :'thread_profiler' => Proc.new { !NewRelic::Agent::Threading::BacktraceService.is_supported? }, :'thread_profiler.enabled' => Proc.new { !NewRelic::Agent::Threading::BacktraceService.is_supported? } } end diff --git a/lib/new_relic/agent/configuration/security_policy_source.rb b/lib/new_relic/agent/configuration/security_policy_source.rb index 21faebb2f2..a9e36ca566 100644 --- a/lib/new_relic/agent/configuration/security_policy_source.rb +++ b/lib/new_relic/agent/configuration/security_policy_source.rb @@ -52,150 +52,150 @@ def change_setting(policies, option, new_value) SECURITY_SETTINGS_MAP = { "record_sql" => [ { - option: :'transaction_tracer.record_sql', - supported: true, - enabled_fn: method(:record_sql_enabled?), + option: :'transaction_tracer.record_sql', + supported: true, + enabled_fn: method(:record_sql_enabled?), disabled_value: 'off', - permitted_fn: proc { |policies| + permitted_fn: proc { |policies| change_setting(policies, :'transaction_tracer.record_sql', 'obfuscated') } }, { - option: :'slow_sql.record_sql', - supported: true, - enabled_fn: method(:record_sql_enabled?), + option: :'slow_sql.record_sql', + supported: true, + enabled_fn: method(:record_sql_enabled?), disabled_value: 'off', - permitted_fn: proc { |policies| + permitted_fn: proc { |policies| change_setting(policies, :'slow_sql.record_sql', 'obfuscated') } }, { - option: :'mongo.capture_queries', - supported: true, - enabled_fn: method(:enabled?), + option: :'mongo.capture_queries', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: proc{ |policies| + permitted_fn: proc { |policies| change_setting(policies, :'mongo.obfuscate_queries', true) } }, { - option: :'transaction_tracer.record_redis_arguments', - supported: true, - enabled_fn: method(:enabled?), + option: :'transaction_tracer.record_redis_arguments', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil } ], "attributes_include" => [ { - option: :'attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil }, { - option: :'transaction_tracer.attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'transaction_tracer.attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil }, { - option: :'transaction_events.attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'transaction_events.attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil }, { - option: :'error_collector.attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'error_collector.attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil }, { - option: :'browser_monitoring.attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'browser_monitoring.attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil }, { - option: :'span_events.attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'span_events.attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil }, { - option: :'transaction_segments.attributes.include', - supported: true, - enabled_fn: method(:not_empty?), + option: :'transaction_segments.attributes.include', + supported: true, + enabled_fn: method(:not_empty?), disabled_value: [], - permitted_fn: nil + permitted_fn: nil } ], "allow_raw_exception_messages" => [ { - option: :'strip_exception_messages.enabled', - supported: true, - enabled_fn: method(:enabled?), + option: :'strip_exception_messages.enabled', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil } ], "custom_events" => [ { - option: :'custom_insights_events.enabled', - supported: true, - enabled_fn: method(:enabled?), + option: :'custom_insights_events.enabled', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil } ], "custom_parameters" => [ { - option: :'custom_attributes.enabled', - supported: true, - enabled_fn: method(:enabled?), + option: :'custom_attributes.enabled', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil } ], "custom_instrumentation_editor" => [ { - option: nil, - supported: false, - enabled_fn: nil, + option: nil, + supported: false, + enabled_fn: nil, disabled_value: nil, - permitted_fn: nil + permitted_fn: nil } ], "message_parameters" => [ { - option: :'message_tracer.segment_parameters.enabled', - supported: true, - enabled_fn: method(:enabled?), + option: :'message_tracer.segment_parameters.enabled', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil } ], "job_arguments" => [ { - option: :'resque.capture_params', - supported: true, - enabled_fn: method(:enabled?), + option: :'resque.capture_params', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil }, { - option: :'sidekiq.capture_params', - supported: true, - enabled_fn: method(:enabled?), + option: :'sidekiq.capture_params', + supported: true, + enabled_fn: method(:enabled?), disabled_value: false, - permitted_fn: nil + permitted_fn: nil } ] } @@ -223,7 +223,7 @@ def build_overrides(security_policies) "Source: #{config_source}" end else - settings[policy[:option]] = policy[:disabled_value] + settings[policy[:option]] = policy[:disabled_value] NewRelic::Agent.logger.info \ "Setting applied: {#{policy[:option]}: #{policy[:disabled_value]}}. " \ "Source: SecurityPolicySource" diff --git a/lib/new_relic/agent/configuration/server_source.rb b/lib/new_relic/agent/configuration/server_source.rb index b5794f9c8b..da66574aa4 100644 --- a/lib/new_relic/agent/configuration/server_source.rb +++ b/lib/new_relic/agent/configuration/server_source.rb @@ -33,7 +33,7 @@ class ServerSource < DottedHash "trusted_account_key" ] - def initialize(connect_reply, existing_config={}) + def initialize(connect_reply, existing_config = {}) merged_settings = {} merge_top_level_keys(merged_settings, connect_reply) @@ -78,10 +78,10 @@ def fix_transaction_threshold(merged_settings) EVENT_HARVEST_CONFIG_SUPPORTABILITY_METRIC_NAMES = { :'analytics_events.max_samples_stored' => 'Supportability/EventHarvest/AnalyticEventData/HarvestLimit', :'custom_insights_events.max_samples_stored' => 'Supportability/EventHarvest/CustomEventData/HarvestLimit', - :'error_collector.max_event_samples_stored'=> 'Supportability/EventHarvest/ErrorEventData/HarvestLimit', + :'error_collector.max_event_samples_stored' => 'Supportability/EventHarvest/ErrorEventData/HarvestLimit', :'span_events.max_samples_stored' => 'Supportability/SpanEvent/Limit', :event_report_period => 'Supportability/EventHarvest/ReportPeriod', - :'event_report_period.span_event_data' => 'Supportability/SpanEvent/ReportPeriod', + :'event_report_period.span_event_data' => 'Supportability/SpanEvent/ReportPeriod' } def add_event_harvest_config(merged_settings, connect_reply) @@ -133,19 +133,19 @@ def filter_keys(merged_settings) # do the real enforcement there. def apply_feature_gates(merged_settings, connect_reply, existing_config) gated_features = { - 'transaction_tracer.enabled' => 'collect_traces', - 'slow_sql.enabled' => 'collect_traces', - 'error_collector.enabled' => 'collect_errors', - 'analytics_events.enabled' => 'collect_analytics_events', + 'transaction_tracer.enabled' => 'collect_traces', + 'slow_sql.enabled' => 'collect_traces', + 'error_collector.enabled' => 'collect_errors', + 'analytics_events.enabled' => 'collect_analytics_events', 'custom_insights_events.enabled' => 'collect_custom_events', 'error_collector.capture_events' => 'collect_error_events', - 'span_events.enabled' => 'collect_span_events' + 'span_events.enabled' => 'collect_span_events' } gated_features.each do |config_key, gate_key| if connect_reply.has_key?(gate_key) allowed_by_server = connect_reply[gate_key] - requested_value = ungated_value(config_key, merged_settings, existing_config) - effective_value = (allowed_by_server && requested_value) + requested_value = ungated_value(config_key, merged_settings, existing_config) + effective_value = (allowed_by_server && requested_value) merged_settings[config_key] = effective_value end end diff --git a/lib/new_relic/agent/configuration/yaml_source.rb b/lib/new_relic/agent/configuration/yaml_source.rb index 9d74c789b9..fa5caf4d87 100644 --- a/lib/new_relic/agent/configuration/yaml_source.rb +++ b/lib/new_relic/agent/configuration/yaml_source.rb @@ -17,7 +17,7 @@ class YamlSource < DottedHash def initialize(path, env) @path = path - config = {} + config = {} @failures = [] # These are needed in process_erb for populating the newrelic.yml via @@ -34,7 +34,7 @@ def initialize(path, env) ::NewRelic::Agent.logger.info("Reading configuration from #{path} (#{Dir.pwd})") raw_file = File.read(@file_path) erb_file = process_erb(raw_file) - config = process_yaml(erb_file, env, config, @file_path) + config = process_yaml(erb_file, env, config, @file_path) rescue ScriptError, StandardError => e log_failure("Failed to read or parse configuration file at #{path}", e) end @@ -63,8 +63,8 @@ def validate_config_file_path(path) end def warn_missing_config_file(path) - based_on = 'unknown' - source = ::NewRelic::Agent.config.source(:config_path) + based_on = 'unknown' + source = ::NewRelic::Agent.config.source(:config_path) candidate_paths = [path] case source @@ -104,10 +104,10 @@ def process_erb(file) def process_yaml(file, env, config, path) if file confighash = if YAML.respond_to?(:unsafe_load) - YAML.unsafe_load(file) - else - YAML.load(file) - end + YAML.unsafe_load(file) + else + YAML.load(file) + end unless confighash.key?(env) log_failure("Config file at #{path} doesn't include a '#{env}' section!") @@ -151,7 +151,7 @@ def log_failure(*messages) messages.each { |message| @failures << message } end - def dot_flattened(nested_hash, names=[], result={}) + def dot_flattened(nested_hash, names = [], result = {}) nested_hash.each do |key, val| next if val == nil if val.respond_to?(:has_key?) && !CONFIG_WITH_HASH_VALUE.include?(key) diff --git a/lib/new_relic/agent/connect/request_builder.rb b/lib/new_relic/agent/connect/request_builder.rb index 289bd75cee..1bf943ca6a 100644 --- a/lib/new_relic/agent/connect/request_builder.rb +++ b/lib/new_relic/agent/connect/request_builder.rb @@ -8,9 +8,7 @@ module NewRelic module Agent module Connect - class RequestBuilder - def initialize(new_relic_service, config, event_harvest_config, environment_report) @service = new_relic_service @config = config @@ -18,24 +16,23 @@ def initialize(new_relic_service, config, event_harvest_config, environment_repo @environment_report = sanitize_environment_report(environment_report) end - # Initializes the hash of settings that we send to the # server. Returns a literal hash containing the options def connect_payload { - :pid => $$, - :host => local_host, - :display_host => Agent.config[:'process_host.display_name'], - :app_name => Agent.config[:app_name], - :language => 'ruby', - :labels => Agent.config.parsed_labels, + :pid => $$, + :host => local_host, + :display_host => Agent.config[:'process_host.display_name'], + :app_name => Agent.config[:app_name], + :language => 'ruby', + :labels => Agent.config.parsed_labels, :agent_version => NewRelic::VERSION::STRING, - :environment => @environment_report, - :metadata => environment_metadata, - :settings => Agent.config.to_collector_hash, + :environment => @environment_report, + :metadata => environment_metadata, + :settings => Agent.config.to_collector_hash, :high_security => Agent.config[:high_security], - :utilization => UtilizationData.new.to_collector_hash, - :identifier => "ruby:#{local_host}:#{Agent.config[:app_name].sort.join(',')}", + :utilization => UtilizationData.new.to_collector_hash, + :identifier => "ruby:#{local_host}:#{Agent.config[:app_name].sort.join(',')}", :event_harvest_config => @event_harvest_config } end @@ -48,9 +45,9 @@ def sanitize_environment_report(environment_report) environment_report end - def environment_metadata + def environment_metadata env_copy = {} - ENV.keys.each {|k| env_copy[k] = ENV[k] if k =~ /^NEW_RELIC_METADATA_/} + ENV.keys.each { |k| env_copy[k] = ENV[k] if k =~ /^NEW_RELIC_METADATA_/ } env_copy end diff --git a/lib/new_relic/agent/connect/response_handler.rb b/lib/new_relic/agent/connect/response_handler.rb index c6995f632b..e87d2cd67e 100644 --- a/lib/new_relic/agent/connect/response_handler.rb +++ b/lib/new_relic/agent/connect/response_handler.rb @@ -2,13 +2,10 @@ # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. - module NewRelic module Agent module Connect - class ResponseHandler - def initialize(agent, config) @agent = agent @config = config diff --git a/lib/new_relic/agent/custom_event_aggregator.rb b/lib/new_relic/agent/custom_event_aggregator.rb index 80fc3c8970..aabf36242b 100644 --- a/lib/new_relic/agent/custom_event_aggregator.rb +++ b/lib/new_relic/agent/custom_event_aggregator.rb @@ -10,9 +10,9 @@ module Agent class CustomEventAggregator < EventAggregator include NewRelic::Coerce - TYPE = 'type'.freeze - TIMESTAMP = 'timestamp'.freeze - PRIORITY = 'priority'.freeze + TYPE = 'type'.freeze + TIMESTAMP = 'timestamp'.freeze + PRIORITY = 'priority'.freeze EVENT_TYPE_REGEX = /^[a-zA-Z0-9:_ ]+$/.freeze named :CustomEventAggregator @@ -46,10 +46,9 @@ def record(type, attributes) def create_event(type, priority, attributes) [ - { TYPE => type, - TIMESTAMP => Process.clock_gettime(Process::CLOCK_REALTIME).to_i, - PRIORITY => priority - }, + {TYPE => type, + TIMESTAMP => Process.clock_gettime(Process::CLOCK_REALTIME).to_i, + PRIORITY => priority}, AttributeProcessing.flatten_and_coerce(attributes) ] end @@ -72,9 +71,9 @@ def note_dropped_events total_count, dropped_count def record_supportability_metrics total_count, captured_count, dropped_count engine = NewRelic::Agent.instance.stats_engine - engine.tl_record_supportability_metric_count("Events/Customer/Seen" , total_count) - engine.tl_record_supportability_metric_count("Events/Customer/Sent" , captured_count) - engine.tl_record_supportability_metric_count("Events/Customer/Dropped", dropped_count) + engine.tl_record_supportability_metric_count("Events/Customer/Seen", total_count) + engine.tl_record_supportability_metric_count("Events/Customer/Sent", captured_count) + engine.tl_record_supportability_metric_count("Events/Customer/Dropped", dropped_count) end def note_dropped_event(type) diff --git a/lib/new_relic/agent/database.rb b/lib/new_relic/agent/database.rb index 2448eb410b..ba5438487b 100644 --- a/lib/new_relic/agent/database.rb +++ b/lib/new_relic/agent/database.rb @@ -9,17 +9,17 @@ module NewRelic # columns for a mysql explain plan MYSQL_EXPLAIN_COLUMNS = [ - "Id", - "Select Type", - "Table", - "Type", - "Possible Keys", - "Key", - "Key Length", - "Ref", - "Rows", - "Extra" - ].freeze + "Id", + "Select Type", + "Table", + "Type", + "Possible Keys", + "Key", + "Key Length", + "Ref", + "Rows", + "Extra" + ].freeze module Agent module Database @@ -57,7 +57,7 @@ def set_sql_obfuscator(type, &block) Obfuscator.instance.set_sql_obfuscator(type, &block) end - def record_sql_method(config_section=:transaction_tracer) + def record_sql_method(config_section = :transaction_tracer) key = record_sql_method_key(config_section) case Agent.config[key].to_s @@ -87,11 +87,11 @@ def record_sql_method_key(config_section) RECORD_FOR = [:raw, :obfuscated].freeze - def should_record_sql?(config_section=:transaction_tracer) + def should_record_sql?(config_section = :transaction_tracer) RECORD_FOR.include?(record_sql_method(config_section)) end - def should_collect_explain_plans?(config_section=:transaction_tracer) + def should_collect_explain_plans?(config_section = :transaction_tracer) should_record_sql?(config_section) && Agent.config["#{config_section}.explain_enabled".to_sym] end @@ -185,7 +185,7 @@ class Statement DEFAULT_QUERY_NAME = "SQL".freeze - def initialize(sql, config={}, explainer=nil, binds=nil, name=DEFAULT_QUERY_NAME, host=nil, port_path_or_id=nil, database_name=nil) + def initialize(sql, config = {}, explainer = nil, binds = nil, name = DEFAULT_QUERY_NAME, host = nil, port_path_or_id = nil, database_name = nil) @sql = Database.capture_query(sql) @config = config @explainer = explainer @@ -205,9 +205,7 @@ def safe_sql Database.obfuscate_sql(self) when :raw sql.to_s - else - nil - end + end end # This takes a connection config hash from ActiveRecord or Sequel and @@ -220,8 +218,6 @@ def adapter elsif @config[:uri] && @config[:uri].to_s =~ /^jdbc:([^:]+):/ # This case is for Sequel with the jdbc-mysql, jdbc-postgres, or jdbc-sqlite3 gems. symbolized_adapter($1) - else - nil end end @@ -247,11 +243,11 @@ def append_sql new_sql private - POSTGIS_PREFIX = 'postgis'.freeze + POSTGIS_PREFIX = 'postgis'.freeze POSTGRES_PREFIX = 'postgres'.freeze - MYSQL_PREFIX = 'mysql'.freeze - MYSQL2_PREFIX = 'mysql2'.freeze - SQLITE_PREFIX = 'sqlite'.freeze + MYSQL_PREFIX = 'mysql'.freeze + MYSQL2_PREFIX = 'mysql2'.freeze + SQLITE_PREFIX = 'sqlite'.freeze def symbolized_adapter(adapter) if adapter.start_with?(POSTGRES_PREFIX) || adapter == POSTGIS_PREFIX diff --git a/lib/new_relic/agent/database/explain_plan_helpers.rb b/lib/new_relic/agent/database/explain_plan_helpers.rb index d92bc051e2..27f1e6756e 100644 --- a/lib/new_relic/agent/database/explain_plan_helpers.rb +++ b/lib/new_relic/agent/database/explain_plan_helpers.rb @@ -9,7 +9,6 @@ module NewRelic module Agent module Database module ExplainPlanHelpers - SUPPORTED_ADAPTERS_FOR_EXPLAIN = [:postgres, :mysql2, :mysql, :sqlite] SELECT = 'select'.freeze @@ -97,7 +96,7 @@ def string_explain_plan_results(results) def process_explain_results_mysql(results) headers = [] - values = [] + values = [] if results.is_a?(Array) # We're probably using the jdbc-mysql gem for JRuby, which will give # us an array of hashes. @@ -118,7 +117,7 @@ def process_explain_results_mysql(results) def process_explain_results_mysql2(results) headers = results.fields - values = [] + values = [] results.each { |row| values << row } [headers, values] end @@ -127,7 +126,7 @@ def process_explain_results_mysql2(results) def process_explain_results_sqlite(results) headers = SQLITE_EXPLAIN_COLUMNS - values = [] + values = [] results.each do |row| values << headers.map { |h| row[h] } end diff --git a/lib/new_relic/agent/database/obfuscation_helpers.rb b/lib/new_relic/agent/database/obfuscation_helpers.rb index 51e375883a..39af36ff77 100644 --- a/lib/new_relic/agent/database/obfuscation_helpers.rb +++ b/lib/new_relic/agent/database/obfuscation_helpers.rb @@ -20,17 +20,17 @@ module ObfuscationHelpers } DIALECT_COMPONENTS = { - :fallback => COMPONENTS_REGEX_MAP.keys, - :mysql => [:single_quotes, :double_quotes, :numeric_literals, :boolean_literals, - :hexadecimal_literals, :comments, :multi_line_comments], - :postgres => [:single_quotes, :dollar_quotes, :uuids, :numeric_literals, - :boolean_literals, :comments, :multi_line_comments], - :sqlite => [:single_quotes, :numeric_literals, :boolean_literals, :hexadecimal_literals, - :comments, :multi_line_comments], - :oracle => [:single_quotes, :oracle_quoted_strings, :numeric_literals, :comments, - :multi_line_comments], - :cassandra => [:single_quotes, :uuids, :numeric_literals, :boolean_literals, - :hexadecimal_literals, :comments, :multi_line_comments] + :fallback => COMPONENTS_REGEX_MAP.keys, + :mysql => [:single_quotes, :double_quotes, :numeric_literals, :boolean_literals, + :hexadecimal_literals, :comments, :multi_line_comments], + :postgres => [:single_quotes, :dollar_quotes, :uuids, :numeric_literals, + :boolean_literals, :comments, :multi_line_comments], + :sqlite => [:single_quotes, :numeric_literals, :boolean_literals, :hexadecimal_literals, + :comments, :multi_line_comments], + :oracle => [:single_quotes, :oracle_quoted_strings, :numeric_literals, :comments, + :multi_line_comments], + :cassandra => [:single_quotes, :uuids, :numeric_literals, :boolean_literals, + :hexadecimal_literals, :comments, :multi_line_comments] } # We use these to check whether the query contains any quote characters @@ -58,7 +58,7 @@ def obfuscate_single_quote_literals(sql) def self.generate_regex(dialect) components = DIALECT_COMPONENTS[dialect] - Regexp.union(components.map{|component| COMPONENTS_REGEX_MAP[component]}) + Regexp.union(components.map { |component| COMPONENTS_REGEX_MAP[component] }) end MYSQL_COMPONENTS_REGEX = self.generate_regex(:mysql) diff --git a/lib/new_relic/agent/database/postgres_explain_obfuscator.rb b/lib/new_relic/agent/database/postgres_explain_obfuscator.rb index feb773ae0e..f158cc955f 100644 --- a/lib/new_relic/agent/database/postgres_explain_obfuscator.rb +++ b/lib/new_relic/agent/database/postgres_explain_obfuscator.rb @@ -12,7 +12,7 @@ module PostgresExplainObfuscator # Database::Obfuscator class because here we don't look for # backslash-escaped strings. QUOTED_STRINGS_REGEX = /'(?:[^']|'')*'|"(?:[^"]|"")*"/ - LABEL_LINE_REGEX = /^([^:\n]*:\s+).*$/.freeze + LABEL_LINE_REGEX = /^([^:\n]*:\s+).*$/.freeze def obfuscate(explain) # First, we replace all single-quoted strings. @@ -35,7 +35,7 @@ def obfuscate(explain) # All parts of the query that can appear in the explain output are # prefixed with "