Tuesday, 28 October 2014

Early Days with Ansible for Nginx and Elastic Search on EC2

As our new recruitment site, sorted.jobs  edges towards production I have to start thinking more about the infrastructure side of things. The search part of the site uses ElasticSearch which is, by design, insecure if you can find an installation you can use it.  Current best practice seems to be to hide it behind a web server running https, normally Nginx, and use that to control access.

This gives me two sets of machines to configure, the Nginx proxy and the Elasticsearch server, since we're trying to be a grown up company we don't want to do all this by hand every time, so it make sense to script it. In the bad old days we used to do this with the Unix shell, see I said Unix not Linux -that's how old those bad old days were! Now we don't need to do that we can have centralised deployments using a variety of tools  such as Chef, Puppet and johnny-come-lately Ansible.

So why choose Ansible? I have briefly played with Chef, and looked at Puppet for another company, and I seem to remember them being fairly complicated. I did a web search to compare the two and Ansible popped up as well in several cases.

Ansible had a few things going for it ;configuration files are in standard YAML, no client to install, Jinja2 templates -which we are already using- and the words 'easy', 'simple' and 'uncomplicated' came up a lot. So I decided to give it a whirl.

Getting it going

Ansible uses a hosts file (held in /etc/ansible/hosts) to define the servers it wants to talk to. As well as defining hosts you can group them for use in playbooks.

We are running sorted.jobs ElasticSearch on EC2 so the definitions look like :
54.123.123.123 ansible_ssh_user=ansible_user ansible_ssh_private_key_file=ansible_key.pem
you can use either IP addresses or domain names to set up the server.

Running a simple command like `ansible all -m ping`or `ansible all -a "/bin/echo hello"`  will let you test out the definitions.

Once you have the definitions sorted out it is time to get Ansible to actually do something useful, you do this with playbooks. A playbook is basically just a script to tell Ansible what to do when. You run them with ansible-playbook  (e.g. ansible-playbook -v elasticsearch.yml). This caught me out initially as I was looking for an option to pass the playbook to the 'ansible' command.

First Playbook Nginx

This playbook installs Nginx uploads the certificates configuration and password files for https
---
- hosts: es_proxys
  sudo: yes

  tasks:
    - name: Installs nginx web server
      apt: pkg=nginx state=installed update_cache=true
      notify:
        - start nginx

    - name: Upload default ngix certs and conf
      copy: src=./es_proxys/conf.tar dest=/tmp

    - name: Untar
      command: tar xf conf.tar
      register: untarred
      ignore_errors: True

    - name: move to nginx etc
      command: mv conf /etc/nginx

    - name: move to nginx etc
      command: `mv .htpasswd /etc/nginx
      register: https_conf

    - name: Upload proxy vhost
      copy: src=es_proxys/es_proxy dest=/etc/nginx/sites-enabled
      when: https_conf|success
      notify:
        - restart nginx
     
     
  handlers:
    - name: start nginx
      service: name=nginx state=started

    - name: restart nginx
      action: service name=nginx state=restarted
From the top , the names of the tasks should tell you what each one is trying to do :
  1. hosts refer to the hosts -or host groups in the Ansible hosts file we talked about above.
  2. sudo -run this as root.
  3. tasks simply the list of things to do
  4. apt the ansible module for the Ubuntu packaging system
  5. notify call a handler
  6. handlers commands that can be run on demand from tasks, typically used to do things like bouncing servers.
  7. register the result of a command into a variable
  8. when conditionally run a task based on the value of a variable. In the example above  the `mv .htpasswd /etc/nginx` command must have succeeded (and, by implication, the earlier tasks) for the proxy upload to be run.

Basic ElasticSearch

This playybook installs Elasticsearch and sets it up with some extra Elasticsearch plugins and a backup configuration.

As well as the things we saw in the proxy  Playbook there are some new features :
  1. get_url  does what it says on the tin, as you can see it also checks file checksums
  2. changed_when tells Ansible when something has happened, in this case it's used because dpkg will succeed whether or not it installs anything
  3. shell runs a Linux shhell command in the raw, command samitizes it.
  4. cron sets up a cron job.
Note in one case I had to use a raw command (curl in the backup config) as I couldn't get the builtin (get_url) to work for me (horrendous quoting issues.
---
- hosts: es_servers
  sudo: yes

  tasks:
  - name: Installs java JRE
    apt: pkg=openjdk-7-jre-headless state=installed update_cache=true
    register: jre
 
  - name: Download ES
    get_url: url=https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.3.4.deb dest=/tmp/es.deb sha256sum=6a15ab0f8c13574162e98828d7ec0e1155e6136f9d45c54b88e39222bbbd53ca
    register: es_dl
 
  - name: Install ES
    command: dpkg --skip-same-version -i /tmp/es.deb
    register: dpkg_result
    changed_when: "dpkg_result.stdout.startswith('Selecting')"
    when: jre|success and es_dl|success
    notify:
      - start es
   
  - name: Remove ES Attachment plugin
    shell: /usr/share/elasticsearch/bin/plugin -r elasticsearch-mapper-attachments || /bin/true
    register: es_plug_result
    changed_when: "'Removed' in es_plug_result.stdout"
    when: dpkg_result|success
   
  - name: Install ES Attachment plugin
    command: /usr/share/elasticsearch/bin/plugin -i  elasticsearch/elasticsearch-mapper-attachments/2.3.0
    register: es_plug_result
    changed_when: "'Installed' in es_plug_result.stdout"
    when:
    notify:
      - restart es
   
  - name: Remove ES S3 plugin
    shell: /usr/share/elasticsearch/bin/plugin -r elasticsearch/elasticsearch-cloud-aws || /bin/true
    register: es_plug_result
    changed_when: "'Removed' in es_plug_result.stdout"
    when: dpkg_result|success
   
  - name: Install ES S3 plugin
    command: /usr/share/elasticsearch/bin/plugin -i  elasticsearch/elasticsearch-cloud-aws/2.3.0
    register: es_plug_result
    changed_when: "'Installed' in es_plug_result.stdout"
    when:
    notify:
      - restart es
   
  - name: Upload s3 config
    copy: src=./s3_config.json dest=/home/ubuntu
 
  - name: Configure backup for s3
    command: curl -XPUT 'http://localhost:9200/_snapshot/s3_live' -d @/home/ubuntu/s3_config.json
    register: s3_result
    changed_when: "'acknowledged' in s3_result.stdout"
 
  - name: Remove s3 config
    command: rm /home/ubuntu/s3_config.json
 
  - name: S3 cron
    cron: name=s3_bup hour=1 minute=50 job='curl -XPUT "http://localhost:9200/_snapshot/s3_live/snapshot_$(date +\%Y\%m\%d)"'
 
   
  handlers:
  - name: start es
    service: name=elasticsearch state=started
 
  - name: restart es
    service: name=elasticsearch state=restarted

 The Book 

If you want a book there's Ansible Configuration Management I did buy this, but I think you will do just as well with the Ansible documentation.

Friday, 24 October 2014

AngularJS ng-if and ng-show

We use AngularJS to do a lot of the front end on sorted.jobs, at some point I may do some posts on the pros and cons of AngularJS, but for now it's enough to say that -in conjunction with Bootstrap it makes producing a front end pretty easy for a back end developer like me.

Anyhoo one of the joys of Angular is how easy it is to produce a display that varies depending on the data provided to it (even dynamically -although that's not the subject of this post). When we started sorted.jobs the way to do this was via ng-show and ng-hide, which basically twiddles the CSS display property for the element to show or hide it. This works very well, but the element would always be fetched from the server, it just wouldn't appear on the screen.

Now we have ng-if, this will remove the element from the DOM altogether if the expression evaluates to false, and so, assuming it is some some of resource it won't fetch it from the server, thus speeding up the page.

Quick Example

ng-show :
<img ng-show="job.user_id && !job.system.logo_url" ng-src="/logo/{{job.user_id}}/{{job_id}}" class="img-responsive">

ng-if :
<img ng-if="job.user_id && !job.system.logo_url" ng-src="/logo/{{job.user_id}}/{{job_id}}" class="img-responsive">

The ng-show in this case has a particularly bad effect in that it will load, although hide, an image that isn't there, i.e. one with no user_id!

References :

ng-if in Angular Docs
Stackexchange -you may want to read this if unexpected things start happening with ng-if, like some other Angular commands it has a habit of creating child scopes.

Thursday, 2 October 2014

AngularJS, Google Search and SEO

Our new site sorted.jobs is now in a stealthy, pre-launch mode, so it is time to start thinking about getting it into the various search engines -especially the big one.

AJAX

Our Job Posts are normally served as AngularJS views -which Google can't parse, since they are AJAX based (although interestingly it can render them with Google Fetch) . However, Google can be persuaded to fetch another version of the page and index that by including this meta tag in the head :

<meta name="fragment" content="!">

If the crawler sees this tag it will then resend the original request with ?_escaped_fragment_= tacked on the end (more here : https://prerender.io/js-seo/angularjs-seo-get-your-site-indexed-and-to-the-top-of-the-search-results/)

so
http://www.sorted.jobs/job_post/UX+Developer/ULKYpZTSSRqBGvGirp_yOQ 
would become
http://www.sorted.jobs/job_post/UX+Developer/ULKYpZTSSRqBGvGirp_yOQ?_escaped_fragment_=

on the server side in the handler I recognise the second form and render a page that is HTML only.

SEO

Since the user doesn't see this page  it doesn't need the full functionality of the original  and we also have the chance to tweak the page to do things like providing a more meaningful <title> and a <meta name=description> tag which Google can do things with as per this snippet post

 Testing and Webmaster Tools

One minor 'gotcha' that we found was with Webmaster tools, in as much as the stats aren't up to date -according to tools we have 0 pages indexed wheres a site specific google search (site:sorted.jobs) shows us  the ten pages we expect.

A second issue is that the 'Fetch' functionality within Webmaster Tools doesn't fire off the second request automatically -so you can't see the page Google would actually index from sorted.jobs on the Fetch results page, just the originally requested AngularJS page.

On the plus side if you 'Fetch' the page you can check that the <meta name="fragment" content="!"> is in the content, and if it is you can then 'Submit to Index' which will kick off Google's crawler on your page and put it into their index within minutes.

Thursday, 4 April 2013

TDD - WTF?

Test Driven Development -good or bad? A friend went for an interview recently with a leading agile consultancy, and their mantra was 'we don't want documentation -we just want TDD'. I was mulling this over and I don't agree.


'Pull the switch' -but will it work?

Documentation -all bad?

There are two problems with documentation :
  • It's always out of date.
  • No one reads it.
Too much documentation is a bad thing -I once worked on a project where we had to document everything in pseudo code at the head of each file. It was disastrous, code reviews were done on the pseudo code, rather than the real thing, it was always out of date, and you wrote the same thing twice -but differently because you ran into language features that forced you away from the pseudo code. In an extreme case I thought of a better way of doing things and implemented that rather than the pseudo code, the boss wasn't happy, but it did stay in production for at least a decade. The pseudo code also  didn't stop people doing stupid things, like implementing their own version of malloc() -which leaked like a sieve.

On the other hand I worked on another system with no documentation at all, even the output was in Dutch, a language I don't understand at all. I didn't need tests to tell me it was failing -it broke completely, pretty much everywhere; but I could have done with something telling me what it was trying to achieve, especially since there was the possibility of a big bang if it all went wrong.

On the other hand good documentation addresses the 'why' rather than the 'what' and 'how' of the code. It should tell us what a function is for or why we chose a non-obvious way to implement something, or highlight a kludge.

Oh yes, RTFM -you know it makes sense.

Testing -all good?

Well yes, generally, although not without cost, test suites have to be developed and maintained and sod's law says that the one thing that breaks there won't be a test for, but that is when you create regression tests. So unit tests, acceptance tests, regression tests you need them all.

If there is a downside it is an excessive focus on test results. Development teams can have a habit of thinking that their job is done when all the tests pass; clients tend to get annoyed if the system still isn't doing what they think it should.  They can also fix failing tests without regard to the rest of the system, 'ok test 1234 went green, but now everything is 50% slower? You think that's acceptable?'

Test Drive Development then?

I think it can work as part of a development process, but it really only addresses the 'what'; as in, 'what is this code doing right now', passing or failing? It says nothing about why the bit of code is there or even how it works and how well it works, in the language of my youth -it's  very 'bottom up', an approach that was being maligned with good reason thirty years ago.

If you fit it into a larger process -say Agile Modeling or BDD, where you have ended up with user stories, tasks and all the rest, then TDD is a valid way to go, although personally I don't think it's any better than writing code and creating unit tests afterwards. I suppose the advantage here would be that with TDD you would create the tests, otherwise you may not, as with documentation there's always something more interesting to do, but it still seems to me to encourage looking at trees rather than the whole wood.

Would I use TDD?

I have given it a go on a couple of small projects, but in the end I fell back to coding first and writing the tests second, it just seems a much more natural way of doing things. I may refactor a lot at times, and this would mean rewriting many of the tests as well. I guess I like to get a prototype working and the go back and revise towards an optimal solution, at which point I'd put in the tests. How about you?

Monday, 25 March 2013

Mobile Implementation Plan

It's almost time to start coding our  mobile  app! But we need an implementation plan.

The plan is -there is no plan. Or as we used to say diving -plan the dive, change the plan! Which is why I spent half an hour in the Port Napier sitting in a corridor waiting for the mud to settle on one occasion, and spent 30 minutes another time getting a singularly dull view of the bottom of the hull. Both times we missed the excellent dive through the middle of it.

Mucked it up twice and it's so big!


Both these times proper application of the 5 Ps would have resulted in a good dive, or even the ability to tell left from right on the second dive. That's Proper Planning Prevents Poor Performance to the uninitiated, for the initiated there's a sixth P -but this is a family blog.

Time for a plan then?

Well no, not a formal one anyway, it's easy to start planning too soon. I was working at GEC when the Nimrod AEW project collapsed, fortunately not for that bit, but £1 billion, in 1980s money! Part of the problem, I was told at the time, was the early specification of the hardware, and requirements that changed.

Anyway we're all Agile and Scrum now, we don't have plans we have backlogs, we don't have delivery dates we have sprints. So, in the spirit of Agile we'll start a product backlog and a sprint backlog although the latter will be pretty flaky as I don't know how much time I'll have to spend on this.

Or should we go Lean?

If I was in the day job, leading the team, we'd have a bunch of meetings to thrash out the product backlog with the rest of the business, playing by MoSCoW rules. Next we'd get together as a team, do the poker planning and work out what would go into the sprint. Since we're a self-managing team people would take ownership of tasks (unless I decided otherwise -that's what they pay me for.) and we'd disappear into our sprint.

But you know what? It's just me, I think we'll just have a list. Since we're at an early stage and just getting used to the technology we can start with :
  1. Get camera working from within app.
  2. Save image.
  3. Upload image (somewhere).
and that gets us to the holy grail of the Minimal Viable Product!

Friday, 8 March 2013

Mobile Scanners - The Competition

In this post we take a look at the competition. One of the drawbacks of the app stores is that there is an app for everything and sure enough it took seconds to find a couple.

CamScanner



Camscanner Screenshot
Camscanner Screenshot


  • Scanning good, easy to use.
  • I don't like the layout of the home page.
  • Cloud integrated with their own cloud storage
  • PDF generated
  • no OCR, or if there is it's well hidden
  • Website so-so, nice and simple to the extent that it's using the back button for navigation, seems like it's a bit of a Beta.
  • App is missing confirmation here and there, e.g. pressed sync nothing happened. It did sync but I couldn't tell without looking on the web site.

 

Handy Scanner

Handy Scanner Screenshot
Handy Scanner Screenshot

Handy scanner in play store
  • Basic scanning and sharing.
  • PDF generated
  • No organisation of documents
  • No cloud storage.
  • Simple but limited. 

Both of these apps do a decent job of capturing the image and doing some basic alignment and cleanup. With both you can easily share the document, that's the point at which HandyScanner stops. Camscanner carries on with some basic groupings, but they don't seem very helpful, you can add notes which is useful and missing from my app, but you can only tag on the website.

I think that this leaves me room for better document organisation and tagging and also for introducing OCR. That said, if you use Google Drive as storage it will attempt to OCR the document, although it failed with both my test examples.

Should I carry on, or give up and wait until Google runs our whole lives? Why is it not surprising their data centre software is called Borg, Orwell could only dream.

Mobile Design Patterns

despite my rant, I am here to design and build, (or rather build and design, since I'm a techie and not a fluffie) a mobile app so it would be good to look at some navigation patterns for it, with a view to stealing them.

We were pointed to http://www.mobiledesignpatterngallery.com as a source of inspiration and asked to pick out 3 relevant ideas.

Home Screen

How about this for a home screen?
  • This roughly matches my idea for a home screen.
  • It might be better to split search from capture in the way notification and search are split here.
  • Use of colour and icons is good, even if the colours themselves are a bit insipid.
  • The numbers against the icons could represent documents stored against a tag for me.

Tabbed Screen

Listings
I hadn't thought of this, but it's a good way of expanding the desktop beyond the screen.
  • Could be good for listing tags and the documents belonging to them
  • Limited number of tags across the top but could swipe
  • Scroll down documents
  • We already had concepts of place and time in the original design

Search Results

Filtered search

I thought this might do for the search results :
  • Icons would be tags allowing you to filter the search
  • Would anyone use it?
  • Techies love search driven sites.
  • Users only use Google.
  • Is it better than the foursquare screen, which could be adapted to the same job
  • Is the overlay too big, although what's underneath isn't what the user wants to see?

 Answers on a postcard please

  • Do users use the search in a mobile app? They don't use site specific search on the web.
  • Is swiping and scrolling going to make users of the tabbed screen seasick?

linkedin