A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

How to do logging and monitoring

A Logging Standard

Format

Use JSON

  • Human readable(ish)
  • Machine readable
  • Abundant tooling
    • jq
    • Document stores like Elastic Seach
    • almost every programming langauge

Common Data Structures

Interoperability enhanced by adopting consistent data structures (detailed below).
Include Provenance IDs.

Provenance IDs

What is a Provenance ID?

  • Provide a Universally Unique ID (but not a UUID)
  • Provide a calling context
    • Clear relationship between a parent ID and its children.

ID Generation

If a provenance ID is provided with a request, use it as the parent of all work.
If no ID is found, generate a new ID from your service's Base ID and use it.

Adoption patterns

As services add support, we will be able to make connections between systems, but no system will fail to track traffic while waiting for upstream services to implement tracking.

Web Service Implementation

HTTP/HTTPS services need to check for the X-Bean-ProvenanceId header.

Structure

  • Base ID 
    • Any alpha-numeric string
    • Something like "SuperProductTypeCGI"
    • One scheme that works well is "Product-Service" like "ABC-Superprod"
  • Unique Element
    • Any string that provides uniqueness
    • UUID is convenient, base64 encoding can keep it shorter.
    • But any string that is unique across multiple systems running with the same base ID.
  • Request Path
    • Each child request adds a segment with a monotonically increasing value.
    • So the first child gets any natural number.  Typically 1
    • Any subsequent children must get a larger number. Typically the previous value, incremented by one.
    • Local and remote children can have separate or shared counters.
    • New items are appended as a comma delimited list.

ABNF Grammar

provenance-id = base-id "." unique-element request-path

base-id = ALPHA *safe-character

unique-element = *safe-character

request-path = ":" request-list
request-path =/ ""

request-path = local-request request-tail
request-path =/ remote-request request-tail

request-tail = "," 
request-tail =/ ""

local-request = number

remote-work = number "r"

number = non-zero-digit *DIGIT

non-zero-digit = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"

safe-character = ALPHA / DIGIT / safe-symbol

; Any printing, non-alphanumeric character isn't ,: or whitespace
safe-symbol =  "!" / DQUOTE / "#" /"$" / "%" / "^" / "&" / "'" / "(" ")" / "*" / "+"
safe-symbol =/ "-" / "." 
safe-symbol =/ "/"
safe-symbol =/ "<" / "=" / ">" / "?" / "@"
safe-symbol =/ "[" / "\" / "^" / "_" / "`"
safe-symbol =/ "{" / "|" / "}" / "~"

Example

Base ID:  ABC-Superprod
Unique Element: 8ed56f13-bd6c-4f47-a8eb-94604e07e6ac
  • New request from customer: ABC-Superprod.8ed56f13-bd6c-4f47-a8eb-94604e07e6ac
  • Internal call to client config: ABC-Superprod.8ed56f13-bd6c-4f47-a8eb-94604e07e6ac:3
  • Client config looks at User config: ABC-Superprod.8ed56f13-bd6c-4f47-a8eb-94604e07e6ac.3.12r

Log Entry Objects

Log Item Types

Log Entry

[ Log Header, Log Body ]

Log Header

[   ISO8601-Time with milliseconds in UTC,
    Log Type Name, 
    hostname,
    program name,
    process ID, 
    thread ID,
    Provenance ID,
    Context name
]

Log Body

{   Log Type Name => Log Type Data,
    file => name of file where log entry generated,
    line => line number of log entry,
    method => name of method/function that generated the entry,
}

Event

Type Name: EVENT
{    message => A string describing the event
}

Unit Of Work

Type Name: UOW
{   start    => ISO6801 date time stamp with milliseconds
    end      => ISO6801 date time stamp with milliseconds
    duration => duration in milliseconds, integer value
    result   => result type identifier
    metrics  => dictionary, keys are strings values are metric objects
    values   => dictionary, keys are strings, values are strings
}

Metric

{    units => string
     count => integer, the number of times the metric was incremented
     total => sum of all values assigned to the metric
}   

Result Types

NORMAL -  successful completion of work
INVALID - Unit of Work terminated improperly
FAILURE - Unit of Work could not be completed, for example, the requested file does not exist.
EXCEPTION - Unit of Work generated an exception and could not be completed.

What Next?

Early to Mid-November

  • Review Object definitions
  • Prepare JSON Schema for object definitions
  • Prepare enhanced demo.
  • Meet with Tech Teams (US and UK) and cover proposal.

The Future

  • Collate feedback from Tech Teams.
  • Finalize object and document all data structures
  • Adapt Log::Work to work with existing BB logging facilities
  • Work with Operations to ensure that their tools can digest generated logs
  • Work with other teams to get adoption of the standard
  • Create Provenance ID tooling in Node.  
    • Should client side code be able to generate Provenance IDs?
      • Lean strongly towards "no" - risk of duplicate IDs being injected maliciously.  
      • Instead use session IDs as a correlation ID for UI interaction.
      • Extending tracking would be nice, but need a way to do it safely.
  • Set up proxies/firewalls to strip provenance ID headers from outgoing requests/responses.
    • May need exceptions to handle cases where data round trips through customer servers/services.

See Also

^ Thanks to Hypno-Mark for the section above ^
Types of logging events

0. Requests & responses

Code lives at framework level, should be tracked in ElasticSearch ONLY. 
For all apps.

1. Unexpected exception

Caught by framework, i.e. application crashes, should be tracked in Sentry
Fail-safe catch-all, very useful

2. Expected fatal exception

Programmed in deliberately, "should never happen, but just in case", should be tracked in Sentry
Quite rare, but always some action required by devops.

3. Expected non-fatal, actionable error

Programmed in deliberately, "action required by devops", should be tracked in Sentry

4. Expected non-fatal non-actionable error

Programmed in deliberately, "no action required", should NOT go to Sentry, only to ElasticSearch.
3 & 4 are often confused with each other, leading to an alerts system polluted with non-actionable events.

5. Expected WARN or INFO level events

Also desirable to track these. Programmed in deliberately, should NOT go to Sentry, only to ElasticSearch.

Systems

Which systems contain data about events?
  • Grafana - metrics only (i.e. a number not a string, so no error messages here).
  • EKK stack (ElasticSearch, Amazon Kinesis, and Kibana) - receives ndjson files.
  • Sentry - supposed to handle urgent events that require an action, but may be polluted over time with non-actionable events.
  • S3 - some applications may send a complete decoded copy of the request/response to an S3 bucket for future reference

^ Will's work above ^

Reserved keywords - Do Not Use these in your code

Do not use these names, you will get confusing errors...

Perl:

  • sub import


Mojolicious:

  • stash('data', ...)



Notes on "The Principles of Clean Architecture" by Uncle Bob Martin

Notes on "The Principles of Clean Architecture" by Uncle Bob Martin


Shows Rails app structure on slide.  Why do I know this is a Rails app?  Why doesn't it tell me what the application does?  What's important about the app is hidden by the structure of the framework.  Why is the web (merely a delivery mechanism) central to the application structure.  Back in the 90's we thought the web changed everything, but it didn't.  We were duped into thinking that the web was an architecturally significant part of an application.  Shows blueprints of library and church.  The use is clear from the structure.

Suggests that Architecture is about Intent.  It's not about tools or libraries, those are details that should be hidden.

Recalls Ivar Jacobsen's classic book Object-Oriented Software Engineering: A Use Case Driven Approach.  Use Cases are like User Stories.  Best kept simple and high level.

Application specific rules (use cases) may be represented with "interactor" objects.
Cross application rules are represented in "entities".

Interface/Boundary objects/classes (act like java interfaces) provide a way for external systems to present requests.

Request model is passed thru boundary into interactor.  Interactors process request and control entities and gather results and emit response object thru interface to delivery system.

Looks like MVC but is NOT because MVC is misunderstood.

MVC is oldest pattern (predates patterns).  MVC is not an architecture.

Defines MVC as originally described in the 70s.  Model object hides a very small business rule.  There is a controller that is connected to an input device like a keyboard or mouse.  Controller sends input to model.  The view registers with the model, which sends state updates to the view, to trigger updates.  MVC was done in the *small*.  You had an MVC for *a button*.

Now we have MVC for whole pages etc, because:  What happens to any kind of good idea in software is that people know that it's a good idea and they also know that their ideas are good.  And so they figure that their ideas are that idea...and they completely lose the original idea.

Problem in app scale:  Poor boundaries.  Not clear what is view, controller or model logic.  Unless you keep extremely careful discipline the concerns will get mixed.

Talks about Plug In pattern.

Dependencies flow only one direction between a plug in and the application.

Changes in a plug in can not impact the core aplication.

Protect you business rules/core application by treating UI and data storage as plug ins.

Things that change frequently should be plugins.

Talk about model View Presenter.  Presenter gets data from app across plugin boundary.  Feeds data to view model.  View renders view model and updates presenter with UX events.

What about the Database?  We put it central to a lot of our architecture.  Because Oracle fooled us all.

The DB is a storage detail and should be abstracted away.

Use a boundary class that handles every query you might want to make.  The DB code should all live across the plug in boundary.  All SQL, etc generated in the plug in.

This architecture helps with testing, because you can easily remove the DB.

Case study:  Deferring a feature out of existence.

Worked on project called Fitnesse (a wiki, which shows test results).  They were going to build it based on MySQL, but they decided to wait and worked on Wiki text to HTML and used a mock DB.  Next they needed to do links and navigation, and so thought they were going to do DB storage.  Instead they just used a mock class that stored pages in RAM.  Then they needed to do start up and shut down, and so they were going to add DB support.  Instead they made their mock object serialize the hash to the file system.  That worked well enough, so they eventually shipped the product without database support.

Eventually they added MySQL support for a customer, but even they gave up on the DB.

Lessons:

*A good architecture allows major decisions to be deferred.*

*A good architecture maximizes the number of decisions NOT made.*

*Achieve that by using a plugin model.*

Use cases form the center of the application.

UI, Datastorage, Frameworks, etc are all external to the use cases.

Remember:  Framework authors will screw you.  You make a tremendous commitment to a framework when you adopt it.  The framework author makes NO commitment to you.

Use frameworks because they are powerful and can make you productive.

But don't follow the examples, because the framework author is going to be comfortable with too much coupling to their framework.

Frameworks are great, but keep them at length.

-- Notes by Mr Swayne.

Use cpm to manage your Perl dependencies

cpm is much faster than cpanm because it makes HTTP requests in parallel and caches modules between runs. The output is also infinitely more clear than cpanm.

# Define the local lib directory
unset PERL5LIB; unset PERL_LOCAL_LIB_ROOT; eval $(perl -Mlocal::lib=./local)

# Install cpm using cpanm
cpanm -nf -L local App::cpm # 35 modules

# Then manually install any problematic modules (as necessary) that have been moved in/out of core
cpm install Module::Build
cpm install Module::Pluggable
cpm install Archive::Extract
cpm install CGI::Cookie
cpm install CGI

# Finally fetch all the CPAN and other dependencies
export DARKPAN=https://username:passwork@mydarkpan.example.com
cpm install --resolver 02packages,$DARKPAN --resolver metadb

Note: --resolver is experimental. The standard argument is --mirror

Thanks HypnoMark

# Another form
cpm install --show-build-log-on-failure --resolver metadb --resolver 02packages,$PINTO_MIRROR --feature=client

# s/PINTO_MIRROR/DARKPAN/

Python basics

Most basic: Use the latest Python 3 (or higher)

Use multiple lines in a one-liner with \n:
echo -e "import sys\nsys.exit('Error')" | python3