Eloquent HasManyThrough 5.5 functionality with version 5.1

The 5.1 version of HasManyThrough is limited; you cannot specify the key on the final table that connects it to the intermediate table.

If you’re unfortunately stuck on 5.1 but want this functionality, the following HasManyThrough should help. Tested with normally loading the relationship (ie modelInstance->relationship) and using with (ie model::with('relationship')->where()), not yet with has or whereHas.

<?php
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;


/**
 * A custom version of HasManyThrough upgrading Eloquent 5.1 HasManyThrough to the 5.5 version.
 * This allows us to specify the key on the intermediate table connecting to the final table.
 */
class CustomHasManyThrough extends HasManyThrough {

    /**
     * The "through" parent model instance.
     *
     * @var \Illuminate\Database\Eloquent\Model
     */
    protected $throughParent;

    /**
     * The local key on the intermediary model.
     *
     * @var string
     */
    protected $secondLocalKey;

    /**
     * Create a new has many through relationship instance.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @param  \Illuminate\Database\Eloquent\Model  $farParent
     * @param  \Illuminate\Database\Eloquent\Model  $throughParent
     * @param  string  $firstKey
     * @param  string  $secondKey
     * @param  string  $localKey
     * @param  string  $secondLocalKey
     * @return void
     */
    public function __construct($query, $farParent, $throughParent, $firstKey, $secondKey, $localKey, $secondLocalKey){
        $this->localKey = $localKey;
        $this->firstKey = $firstKey;
        $this->secondKey = $secondKey;
        $this->secondLocalKey = $secondLocalKey;

        $this->farParent = $farParent;        
        $this->throughParent = $throughParent;

        Relation::__construct($query, $throughParent);
    }

    /**
     * Get the fully qualified parent key name.
     *
     * @return string
     */
    public function getQualifiedParentKeyName(){
        return $this->parent->getTable().'.'.$this->secondLocalKey;
    }

    /**
     * Set the constraints for an eager load of the relation.
     *
     * @param  array  $models
     * @return void
     */
    public function addEagerConstraints(array $models)
    {
        $table = $this->parent->getTable();
        $this->query->whereIn($table.'.'.$this->firstKey, $this->getKeys($models, $this->localKey));
    }

    /**
     * Match the eagerly loaded results to their parents.
     *
     * @param  array   $models
     * @param  \Illuminate\Database\Eloquent\Collection  $results
     * @param  string  $relation
     * @return array
     */
    public function match(array $models, \Illuminate\Database\Eloquent\Collection $results, $relation)
    {
        $dictionary = $this->buildDictionary($results);
        // Once we have the dictionary we can simply spin through the parent models to
        // link them up with their children using the keyed dictionary to make the
        // matching very convenient and easy work. Then we'll just return them.
        foreach ($models as $model) {
            $key = $model->getAttribute($this->localKey);
            if (isset($dictionary[$key])) {
                $value = $this->related->newCollection($dictionary[$key]);
                $model->setRelation($relation, $value);
            }
        }
        return $models;
    }
}


class CustomEloquent extends Eloquent {

    /**
     * Replace the Eloquent has-many-through relationship with our custom one.
     *
     * @param  string  $related
     * @param  string  $through
     * @param  string|null  $firstKey
     * @param  string|null  $secondKey
     * @param  string|null  $localKey
     * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
     */
    public function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null){
        $through = new $through;
        $firstKey = $firstKey ?: $this->getForeignKey();
        $secondKey = $secondKey ?: $through->getForeignKey();
        $localKey = $localKey ?: $this->getKeyName();
        $secondLocalKey ?: $through->getKeyName();

        return new CustomHasManyThrough((new $related)->newQuery(), $this, $through, $firstKey, $secondKey, $localKey, $secondLocalKey);
    }
}

Getting rancher/server back up after restarting from the web UI

If you restart the rancher/server container from within rancher it sets the state to shutting-down in the database, and then the container stops and the state cannot be updated anymore. If you try and start the server again it will see the state is shutting-down and shut itself down again.

To resolve, from the command line start a new rancher/server container with the same port and database config (but a different name; or let docker pick a random name), go to the web UI and in the Infrastructure/Containers list find your original rancher/server container and try to start it. It will fail (because the port is already allocated), but the state in the database will be updated. Then back on the command line, docker kill the new rancher/server and start up the old one (make sure the name is the same).

That should be it! The rancher/server should successfully be running again.

Connection aborted error using python elasticsearch with large files on AWS ES

AWS ES has an upload limit of 10MB. If you are using the bulk helpers or reindex and some documents are above this limit you will get an error ConnectionError: ('Connection aborted.', error(32, 'Broken pipe')).

To solve it, use the max_chunk_bytes argument, which can be used with reindex like so:

elasticsearch.helpers.reindex(
es, source_index, target_index, chunk_size=100,
bulk_kwargs={'max_chunk_bytes': 10048576},  # 10MB AWS ES upload limit
)

Ideally make the chunk size the average number of documents before the size is 10MB, and then in the case there are some larger documents that push the size over 10MB the elasticsearch library will handle it.

Error running vagrant provisioner when default vagrant share is disabled

If you have disabled the default vagrant shared directory

[sourcecode language=’ruby’]
config.vm.synced_folder ‘.’, ‘/vagrant’, disabled: true
[/sourcecode]

You will get the following error using a provisioner:

[sourcecode]
==> default: Running provisioner: ansible_local…
default: Installing Ansible…
default: Running ansible-playbook…
cd /vagrant && PYTHONUNBUFFERED=1 ANSIBLE_FORCE_COLOR=true ansible-playbook –limit="default" –inventory-file=/tmp/vagrant-ansible/inventory -v /ansible/init.yml
bash: line 3: cd: /vagrant: No such file or directory
Ansible failed to complete successfully. Any error output should be
visible above. Please fix these errors and try again.
[/sourcecode]

To fix, set the provisioning_path configuration:
[sourcecode language=’ruby’]
config.vm.provision “ansible_local” do |ansible|
ansible.provisioning_path = “/ansible”
end
[/sourcecode]

Importing/restoring elastic search snapshot to AWS Elastic Search Service

Took me a long time to find out how to do this.

A few people have re-posted a lot of this AWS article but missed out some crucial details: http://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-managedomains.html#es-managedomains-snapshots

The general idea is:

  1. Create an AWS bucket and put the snapshot files into it (don’t use a subdirectory, the .dat files should be in the bucket root).  No need to change permissions on the bucket or anything.
  2. Create an IAM role and policy as per the documentation in the AWS docs link above.  When creating the role using web management console you need to choose EC2 role type and manually modify the trust relationship after creating it.
  3. Run a python script (can find this in the docs link above) using the boto library to register the bucket as a snapshot repository in ES.  You need to sign the request regardless of the ES access policy you are using.  HOWEVER set `is_secure` to `True`.  Without this I was getting `<html></html>` returned instead of any error messages.
  4. Use curl to do the restore (no need to sign restore/backup requests if your access policy is open / IP-based).  Again check the doc for the exact curl command, but as above use https instead of http to get real error messages.

Mount docker socket inside AWS container

  1. To your container, add a new volume
  2. Name: ‘docker_sock’, source path: ‘/var/run/docker.sock’
  3. In Storage and Logging section, add new mount point
  4. Select ‘docker_sock’, container path: ‘/var/run/docker.sock’

And that’s it. No need to give privileged access, and if you run docker commands directly from inside the container there’s no need to change IAM policy.

Associating EC2 instances with an ECS cluster

The EC2 instance is associated with a Container Service cluster using the /etc/ecs/ecs.config file on the instance, in the format ECSCLUSTER=yourcluster_name.

The EC2 instance must also have the ECS agent installed. If you create the instance using the ECS AMI this will be pre-installed (search for AMI called amazon-ecs-optimized).

This configuration can be put in the User Data field:


#!/bin/bash
echo ECS_CLUSTER=your_cluster_name >>/etc/ecs/ecs.config

To find the setting on an instance that already exists: Actions -> Instance Settings -> View/Change User Data

Exact instructions for setting up the EC2 instance properly can be found here: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/launchcontainerinstance.html

Running high trust apps / plugins with Sharepoint Foundation 2013

The User Profile service is not available on Sharepoint Foundation and therefore high trust apps are not supported.   However I found that after installing a high trust app it worked until restarting IIS, and after that it would generate authentication errors.  Re-uploading the app package to the app site fixed the authentication errors and allowed the app to run properly again.

I could not find an API to automate this re-upload process, so instead it can be done using a headless browser.

Here’s an example in casperjs (note that on Windows casperjs must be installed in a path without spaces):

[sourcecode language=’js’]

var url = ‘https://yourdomain.com/sites/appcatalog/_layouts/15/start.aspx#/AppCatalog/Forms/AllItems.aspx’
var file = ‘sharepoint-package.app’
var user = ‘username’
var pass = ‘password’

var casper = require(‘casper’).create();

casper.start();
casper.setHttpAuth(user, pass);

casper.thenOpen(url, function() {
this.echo(this.getTitle());
this.waitForSelector(‘#idHomePageNewDocument-WPQ2’, function() {
this.echo(“Found selector”);
});
});

casper.thenClick(‘#idHomePageNewDocument-WPQ2’, function() {
this.echo(“Clicked button”);
this.waitForSelector(‘.ms-dlgFrameContainer > iframe’, function() {
this.echo(“Got the iframe”);
});
});

casper.withFrame(1, function() {
this.waitForSelector(‘#aspnetForm’, function() {
this.echo(“Found form”);
this.fill(‘#aspnetForm’, {
‘ctl00$PlaceHolderMain$ctl01$ctl04$InputFile’: file,
}, false);
this.wait(3000, function() {
this.click(‘#ctl00PlaceHolderMainctl00RptControlsbtnOK’);
this.echo(“Clicked button”);
});
});
});

[/sourcecode]

The term ‘Get-SPApplicationPrincipal’ is not recognized as the name of a cmdlet, function, script file or operable program.

Ignore what it says on this technet page: http://technet.microsoft.com/en-gb/library/jj219714(v=office.15).aspx

The command is actually Get-SPAppPrincipal.

You can see the correct command here: http://technet.microsoft.com/en-us/library/jj219664(v=office.15).aspx