python - code quality and production monitoring

77
Code Quality to Monitoring production : use cases and best practices David Melamed Pyweb meetup - September 21, 2014

Upload: david-melamed

Post on 29-Nov-2014

297 views

Category:

Engineering


3 download

DESCRIPTION

About code quality & production monitoring

TRANSCRIPT

Page 1: Python - code quality and production monitoring

Code Quality to Monitoring production: use cases and best practices

David Melamed

Pyweb meetup - September 21, 2014

Page 2: Python - code quality and production monitoring

Agenda

What is good code?

How to measure quality code?

Continuous Integration

How to efficiently monitor production?

Page 3: Python - code quality and production monitoring

About me

Full-stack developer at Cloudlock

Fond of technology & automation

Code Quality Evangelist

Geek on my free time

Page 4: Python - code quality and production monitoring

About CloudlockFounded: 2011

Headquarters: Waltham, Mass. (U.S.)

R&D Headquarters: Tel Aviv

Employees: 80+

Funding: $28M+

700+ Customers 9,600 Unique Apps Discovered

5 million Users under Management

13 billion objects processed daily

Native Cloud Security Solutionsfor SaaS Applications

Selected customersInvestors

Page 5: Python - code quality and production monitoring

What is good code?

Page 6: Python - code quality and production monitoring

Good code is…

Easy to read & understand

Easy to extend

Easy to maintain

Testable

Page 7: Python - code quality and production monitoring

How to write good code?

Page 8: Python - code quality and production monitoring

from xkcd

Page 9: Python - code quality and production monitoring

Good code requires constant

REFACTORING

Page 10: Python - code quality and production monitoring

The Code Quality Star

Coding Standards

Code Review

Automated Tests

CodeComplexity

ArchitectureDesign

Source

Page 11: Python - code quality and production monitoring

Code should be easy to read

Page 12: Python - code quality and production monitoring
Page 13: Python - code quality and production monitoring

Code should be readable

Avoid comments but avoid obvious ones (the code should be self-explanatory)

Avoid comments too verbose

Comments need to be maintained

Page 14: Python - code quality and production monitoring

Coding Standards

Page 15: Python - code quality and production monitoring

The Zen of Python (PEP20)

Beautiful is better than ugly

Explicit is better than implicit

Simple is better than complex

Complex is better than complicated

Readability counts

Page 16: Python - code quality and production monitoring

Coding Style: Readability Counts

“Programs must be written for people to read, and only incidentally for machines to execute.”

Abelson & Sussman, Structure and Interpretation of Computer Programs

Page 17: Python - code quality and production monitoring

PEP8: Style guide for PythonIndentation

Maximum line length

Blank lines

Redundant white spaces

Imports

Comments

Naming conventions

Page 18: Python - code quality and production monitoring

How to check /enforce PEP8

Pycharm (Tools > Flake8)

Git pre-commit hook (http://goo.gl/bteYkq)

Jenkins job for continuous integration

Page 19: Python - code quality and production monitoring

Naming is key

Page 20: Python - code quality and production monitoring
Page 21: Python - code quality and production monitoring
Page 22: Python - code quality and production monitoring

Naming best practises

Adopt a convention and stick with it (fetch vs. retrieve vs. get)

Use intention-revealing names

Avoid misleading readers

Make meaningful distinctions

Use searchable names

Avoid mental mapping

Use domain names

From Clean code, R. Martin

Page 23: Python - code quality and production monitoring

Code Architecture

Page 24: Python - code quality and production monitoring

Best Practices in Code Architecture

OOP

DRY

SOLID

Loose Coupling

Page 25: Python - code quality and production monitoring

Don’t Repeat Yourself (aka DRY)

http://www.sonarqube.org/manage-duplicated-code-with-sonar/

Page 26: Python - code quality and production monitoring

SOLID principles

• SRP: Single Responsibility Principle

• OCP: Open/closed principle

• LSP: Liskov substitution principle

• ISP: Interface segregation principle

• DIP: dependency inversion principle

Page 27: Python - code quality and production monitoring

http://www.codeproject.com/Articles/93369/How-I-explained-OOD-to-my-wife

Page 28: Python - code quality and production monitoring

http://www.codeproject.com/Articles/93369/How-I-explained-OOD-to-my-wife

Page 29: Python - code quality and production monitoring

http://www.codeproject.com/Articles/93369/How-I-explained-OOD-to-my-wife

Page 30: Python - code quality and production monitoring

http://www.codeproject.com/Articles/93369/How-I-explained-OOD-to-my-wife

Page 31: Python - code quality and production monitoring

http://www.codeproject.com/Articles/93369/How-I-explained-OOD-to-my-wife

Page 32: Python - code quality and production monitoring

Loosely Coupled Components

Page 33: Python - code quality and production monitoring

Main principlesSplit components into repositories

Web app: use clean layers

view / endpoint (presentation)

service (business logic)

DAO (model)

Use message bus for communication inter-components (i.e. RabbitMQ)

Use daemons / workers for long-running tasks

Use events / signals to decouple unrelated actions

Microservices

Page 34: Python - code quality and production monitoring
Page 35: Python - code quality and production monitoring

Architecture at Cloudlock

Nginx

AWS VPC

Message Bus (RabbitMQ)

Web Server

API Server

RDS PostgreSQL

ElastiCache Redis

Authentication Gateway

Worker Worker Worker

Logs

Page 36: Python - code quality and production monitoring

Code Reviews

Page 37: Python - code quality and production monitoring
Page 38: Python - code quality and production monitoring

Tools for code review

Github Pull Requests

Review Board

Gerrit

Crucible

Page 39: Python - code quality and production monitoring

Code documentation

Page 40: Python - code quality and production monitoring
Page 41: Python - code quality and production monitoring

Code Testing

Page 42: Python - code quality and production monitoring

Different types of testsManual Test

Unit Test

Integration Test

System Test

Acceptance/Regression Test (end-to-end)

Smoke Test

Page 43: Python - code quality and production monitoring

Unit Test

Test if small, distinct and isolated portions of code are working as expected, provided some input

Mock your dependencies (database, logger, service)

Should be very fast

No need to test EVERYTHING (i.e. private methods)

Frameworks: unittest, pytest and nose

Page 44: Python - code quality and production monitoring
Page 45: Python - code quality and production monitoring

PytestNo need for base class (works both for classes and methods)

More pythonic than unittest

Fixtures (conftest.py)

Parametrized tests

Markers

Various plugins for coverage, bdd, django, twisted…

Used for unit tests, integration tests and end to end tests

Page 46: Python - code quality and production monitoring

Integration TestsTest communication between services

You may mock some of the dependencies depending on what you test

Page 47: Python - code quality and production monitoring

System TestsGlobal test, more functional of the whole system

TestApp (Pyramid app) using a test database

Call the API and test the expected response code

Page 48: Python - code quality and production monitoring

End-to-end testsSplinter: web driver abstraction (firefox, selenium)

splinter-pytest: fixtures for browser

Plugin for rerun flaky tests, tests with steps

Use Selenium Grid to test several browsers

Page 49: Python - code quality and production monitoring

Smoke TestsMake sure the system is alive

Tests that the components are working

Tests that the components can communicate

Health check / status page

Page 50: Python - code quality and production monitoring

Measuring code quality

Page 51: Python - code quality and production monitoring
Page 52: Python - code quality and production monitoring

Code Quality Metrics

Code Standards Violations (pylint /flake8/pyflakes)

LOC (Lines Of Code)

Cyclomatic Complexity

Unit Tests Coverage

Page 53: Python - code quality and production monitoring

Code Coverage

Makes sense only for unit tests

Calculates the coverage based on the paths run by the tests

100% coverage is not a goal on its own

May be misleading regarding the code quality

Page 54: Python - code quality and production monitoring

Unit Test Diff Coverage

Page 55: Python - code quality and production monitoring

Mutation Analysis

From Mutation analysis vs. code coverage in automated assessment of students’ Testing Skills (P. Ihantola)

Page 56: Python - code quality and production monitoring

PylintReport ====== 85 statements analysed. !Duplication ----------- !+-------------------------+------+---------+-----------+ | |now |previous |difference | +=========================+======+=========+===========+ |nb duplicated lines |0 |0 |= | +-------------------------+------+---------+-----------+ |percent duplicated lines |0.000 |0.000 |= | +-------------------------+------+---------+-----------+ !!!Messages by category -------------------- !+-----------+-------+---------+-----------+ |type |number |previous |difference | +===========+=======+=========+===========+ |convention |18 |18 |= | +-----------+-------+---------+-----------+ |refactor |2 |2 |= | +-----------+-------+---------+-----------+ |warning |1 |1 |= | +-----------+-------+---------+-----------+ |error |4 |4 |= | +-----------+-------+---------+-----------+ !!!Messages -------- !+-----------------------------+------------+ |message id |occurrences | +=============================+============+ |line-too-long |10 | +-----------------------------+------------+ |no-name-in-module |4 | +-----------------------------+------------+ |missing-docstring |4 | +-----------------------------+------------+

Global evaluation ----------------- Your code has been rated at 5.18/10 (previous run: 5.18/10, +0.00) !Raw metrics ----------- !+----------+-------+------+---------+-----------+ |type |number |% |previous |difference | +==========+=======+======+=========+===========+ |code |90 |63.83 |90 |= | +----------+-------+------+---------+-----------+ |docstring |30 |21.28 |30 |= | +----------+-------+------+---------+-----------+ |comment |5 |3.55 |5 |= | +----------+-------+------+---------+-----------+ |empty |16 |11.35 |16 |= | +----------+-------+------+---------+-----------+ !!!Statistics by type ------------------ !+---------+-------+-----------+-----------+------------+---------+ |type |number |old number |difference |%documented |%badname | +=========+=======+===========+===========+============+=========+ |module |1 |1 |= |0.00 |0.00 | +---------+-------+-----------+-----------+------------+---------+ |class |2 |2 |= |100.00 |0.00 | +---------+-------+-----------+-----------+------------+---------+ |method |1 |1 |= |100.00 |0.00 | +---------+-------+-----------+-----------+------------+---------+ |function |6 |6 |= |50.00 |33.33 | +————+-------+-----------+-----------+------------+---------+ !!!!!!!!!!

Page 57: Python - code quality and production monitoring

Test Automation

Page 58: Python - code quality and production monitoring

Why do you need automated tests?!

Optimise speed, efficiency and quality

Catch the bugs upfront

Safety net for refactoring

Page 59: Python - code quality and production monitoring
Page 60: Python - code quality and production monitoring

On the Road to Continuous Integration

Page 61: Python - code quality and production monitoring

Several “Continuous” processes

Continuous Integration

Continuous Deployment

Continuous Delivery

Page 62: Python - code quality and production monitoring

Several platforms for CI

Jenkins

Travis CI

Circle CI

Shippable

BuildBot

Page 63: Python - code quality and production monitoring

Continuous Integration FlowFeature Branch

Develop Branch

Updates Github PR

Git Push

Several jobs: - pep8 compliance - unit test - integration test - end to end test

Merge PR

Pull Request

Tag

Deployment

Code Review

Page 64: Python - code quality and production monitoring

Jenkins dashboard

Page 65: Python - code quality and production monitoring
Page 66: Python - code quality and production monitoring
Page 67: Python - code quality and production monitoring

Automated Deployment

Page 68: Python - code quality and production monitoring

Pick the right tool to deploy

AWS ElasticBeanstalk

AWS OpsWorks

Chef

Puppet

SaltStack

Ansible

Page 69: Python - code quality and production monitoring

Ansible

http://terry.im/wiki/terry/attachments/29786135/37552129.png

Page 70: Python - code quality and production monitoring

It works only on my machine

Page 71: Python - code quality and production monitoring

The Docker Project

Run everywhere

Run everything

Advantages:

• Pricing

• Speed

• Unifying environments

• Testability / reproducibility

• Easily add/replace components

Page 72: Python - code quality and production monitoring

Docker on your Mac

http://www.warski.org/blog/2014/05/spray-server-docker-container/docker-stack-5/

Page 73: Python - code quality and production monitoring

Production Monitoring

Page 74: Python - code quality and production monitoring
Page 75: Python - code quality and production monitoring

Production MonitoringAWS CloudWatch

End-to-end tests running in Jenkins

StackDriver

Log analysis (streams)

Page 76: Python - code quality and production monitoring

Questions?

Page 77: Python - code quality and production monitoring

Python developers WANTED

Contact: [email protected]