Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ssh support #13

Open
wants to merge 31 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
16d575b
add ssh_port
Jul 3, 2012
b011cde
Update Deployer/Deployer.php
mikemeier Nov 1, 2012
4b58c78
Merge pull request #1 from mikemeier/patch-1
Dec 28, 2012
0cf86e6
using the correct array keys and check if existing
Dec 28, 2012
23b8902
add default ssh config and give possibility to overwrite the options …
Dec 28, 2012
c2aedce
cd always on each command because ssh2_exec is used
Dec 28, 2012
5237f7a
remove env - moved to symfony_command
Dec 28, 2012
338eb71
Merge pull request #2 from mikemeier/master
Dec 28, 2012
a4e24da
format
Dec 28, 2012
e61bf8f
format
Dec 28, 2012
3d3ce28
add composer.json
Dec 28, 2012
ffb0ffa
Merge pull request #3 from mikemeier/master
mikemeier Dec 28, 2012
af21a38
format
Dec 28, 2012
9b2344a
Merge pull request #4 from mikemeier/master
mikemeier Dec 28, 2012
965d518
Update Deployer/Ssh.php
mikemeier Jan 8, 2013
5273d0e
Update Deployer/Ssh.php
mikemeier Jan 8, 2013
ffc8498
add onDeploymentSshStart eventListener for output
Jan 8, 2013
d51ddb7
allow to export env variables to commands
Jan 9, 2013
35dc89a
remove console requirement
Jan 14, 2013
85d1076
remove target dir
Feb 6, 2013
fc702a8
add target dir
Feb 6, 2013
1935cb7
increase rsync timeout from default 60s to 120s
Feb 13, 2013
ceefcd5
add version
Feb 15, 2013
dbebfbd
allow symfony upgrades
Feb 19, 2013
677cec1
remove version
Feb 20, 2013
2c6c05d
enable git tagging
Mar 5, 2013
06e35a3
Merge branch 'master' of git://github.com/ibrows/BeSimpleDeploymentBu…
Mar 5, 2013
68374f2
also pass real parameter
Apr 11, 2013
a653fd1
add timeout config option to rsync
Nov 15, 2013
f6fe16e
Use psr-4
mikemeier Apr 30, 2014
a1d1136
Ask for arguments like password if not given
Jun 3, 2014
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion BeSimpleDeploymentBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@

class BeSimpleDeploymentBundle extends Bundle
{
}
}
51 changes: 51 additions & 0 deletions Command/DeploymentCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ protected function configure()
$this
->setDefinition(array(
new InputArgument('server', InputArgument::OPTIONAL, 'The target server name', null),
new InputOption('tag', 't', InputOption::VALUE_NONE, 'Tag with git if real deployment')
))
;
}
Expand Down Expand Up @@ -58,6 +59,13 @@ protected function execute(InputInterface $input, OutputInterface $output)
));
});

$eventDispatcher->addListener(Events::onDeploymentSshStart, function (CommandEvent $event) use ($self) {
$self->write(sprintf(
'[Try SSH Command] %s',
$event->getCommand()
));
});

// Feedback events

if ($output->getVerbosity() > Output::VERBOSITY_NORMAL) {
Expand Down Expand Up @@ -86,6 +94,49 @@ protected function execute(InputInterface $input, OutputInterface $output)
), 'info');
});

if($input->getOption('tag')){
$eventDispatcher->addListener(Events::onDeploymentSuccess, function (DeployerEvent $event) use ($self) {
if(!$event->isTest()){
$path = realpath($this->getApplication()->getKernel()->getRootDir().'/..');
if(is_dir($path)){
$tag = 'deploy-'. strtolower($event->getServer());

$self->write(sprintf(
'Trying to set GIT tag %s in %s',
$tag,
$path
), 'comment');

$gitCmd = sprintf(
'git --git-dir=%s --work-tree=%s',
$path.'/.git',
$path
);

$status = shell_exec($gitCmd.' status -s');
if($status !== null){
$self->write(sprintf('There are uncommitted changes - wont set the tag: %s', $status), 'error');
return;
}

$commit = shell_exec($gitCmd.' rev-parse HEAD');
if(!$commit){
$self->write('Last commit-hash not found for HEAD', 'error');
return;
}

$tagResult = shell_exec($gitCmd.' tag -f '. $tag .' '. $commit);
if(!$tagResult){
$self->write('Tagging seems ok. Try "git push --tags"', 'info');
return;
}

$self->write($tagResult, 'info');
}
}
});
}

$eventDispatcher->addListener(Events::onDeploymentRsyncSuccess, function (CommandEvent $event) use ($self) {
$self->write(sprintf(
'[Rsync success] %s',
Expand Down
10 changes: 5 additions & 5 deletions DependencyInjection/BeSimpleDeploymentExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ public function load(array $configs, ContainerBuilder $container)
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('deployment.xml');

$container->setParameter('be_simple_deployment.config.rsync', $config['rsync']);
$container->setParameter('be_simple_deployment.config.ssh', $config['rsync']);
$container->setParameter('be_simple_deployment.config.rules', $config['rules']);
$container->setParameter('be_simple_deployment.config.commands', $config['commands']);
$container->setParameter('be_simple_deployment.config.servers', $config['servers']);
$container->setParameter('be_simple_deployment.config.rsync', isset($config['rsync']) ? $config['rsync'] : array());
$container->setParameter('be_simple_deployment.config.ssh', isset($config['ssh']) ? $config['ssh'] : array());
$container->setParameter('be_simple_deployment.config.rules', isset($config['rules']) ? $config['rules'] : array());
$container->setParameter('be_simple_deployment.config.commands', isset($config['commands']) ? $config['commands'] : array());
$container->setParameter('be_simple_deployment.config.servers', isset($config['servers']) ? $config['servers'] : array());
}

/**
Expand Down
56 changes: 55 additions & 1 deletion DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected function addRsyncSection(ArrayNodeDefinition $node)
->scalarNode('command')->defaultValue('rsync')->cannotBeEmpty()->end()
->booleanNode('delete')->defaultFalse()->end()
->scalarNode('options')->defaultValue('-Cva')->end()
->scalarNode('timeout')->defaultValue(120)->end()
->scalarNode('root')->defaultValue('%kernel.root_dir%/..')->cannotBeEmpty()->end()
->end()
;
Expand All @@ -52,9 +53,34 @@ protected function addSshSection(ArrayNodeDefinition $node)
{
$node->children()
->arrayNode('ssh')->children()
->scalarNode('username')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()

->scalarNode('pubkey_file')->defaultNull()->end()
->scalarNode('privkey_file')->defaultNull()->end()
->scalarNode('passphrase')->defaultNull()->end()
->arrayNode('connect_methods')
->addDefaultsIfNotSet()
->children()
->scalarNode('kex')->defaultNull()->end()
->scalarNode('hostkey')->defaultNull()->end()
->arrayNode('client_to_server')
->addDefaultsIfNotSet()
->children()
->scalarNode('crypt')->defaultNull()->end()
->scalarNode('comp')->defaultNull()->end()
->scalarNode('mac')->defaultNull()->end()
->end()
->end()
->arrayNode('server_to_client')
->addDefaultsIfNotSet()
->children()
->scalarNode('crypt')->defaultNull()->end()
->scalarNode('comp')->defaultNull()->end()
->scalarNode('mac')->defaultNull()->end()
->end()
->end()
->end()
->end()
;
}
Expand Down Expand Up @@ -96,7 +122,7 @@ protected function addCommandsSection(ArrayNodeDefinition $node)
->prototype('array')->children()
->scalarNode('type')->defaultValue('symfony')->end()
->scalarNode('command')->isRequired()->cannotBeEmpty()->end()
->scalarNode('env')->defaultNull()->end()
->arrayNode('env')->prototype('scalar')->end()
->end()
;
}
Expand All @@ -114,8 +140,36 @@ protected function addServersSection(ArrayNodeDefinition $node)
->scalarNode('host')->defaultValue('localhost')->end()
->scalarNode('rsync_port')->defaultNull()->end()
->scalarNode('ssh_port')->defaultValue(22)->cannotBeEmpty()->end()

->scalarNode('username')->defaultNull()->end()
->scalarNode('password')->defaultNull()->end()

->scalarNode('symfony_command')->defaultValue('php app/console')->end()

->scalarNode('pubkey_file')->defaultNull()->end()
->scalarNode('privkey_file')->defaultNull()->end()
->scalarNode('passphrase')->defaultNull()->end()

->arrayNode('connect_methods')
->children()
->scalarNode('kex')->end()
->scalarNode('hostkey')->end()
->arrayNode('client_to_server')
->children()
->scalarNode('crypt')->end()
->scalarNode('comp')->end()
->scalarNode('mac')->end()
->end()
->end()
->arrayNode('server_to_client')
->children()
->scalarNode('crypt')->end()
->scalarNode('comp')->end()
->scalarNode('mac')->end()
->end()
->end()
->end()
->end()
->scalarNode('path')->isRequired()->cannotBeEmpty()->end()
->arrayNode('rules')
->useAttributeAsKey('rules')->prototype('scalar')->end()
Expand Down
10 changes: 4 additions & 6 deletions Deployer/Deployer.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,10 @@ public function test($server = null)
*/
protected function deploy($server = null, $real = false)
{
if(is_null($server)) {
foreach($this->config->getServerNames() as $server) {
$this->deploy($server, $real);
}

return;
if(is_null($server)){
$serverNames = $this->config->getServerNames();
reset($serverNames);
return $this->deploy(current($serverNames), $real);
}

$this->dispatcher->dispatch(Events::onDeploymentStart, new DeployerEvent($server, $real));
Expand Down
5 changes: 5 additions & 0 deletions Deployer/Rsync.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ public function run(array $connection, array $rules, $real = false)

$command = $this->buildCommand($connection, $rules, $real);
$process = new Process($command, $root);
$process->setTimeout($this->config['timeout']);

$this->stderr = array();
$this->stdout = array();
Expand Down Expand Up @@ -150,6 +151,10 @@ protected function buildCommand(array $connection, array $rules, $real = false)
$options[] = '-p '.$connection['port'];
}

if($connection['ssh_port']!=22) {
$options[] = sprintf('--rsh="ssh -p%d"', $connection['ssh_port']);
}

if ($this->config['delete']) {
$options[] = '--delete';
}
Expand Down
108 changes: 59 additions & 49 deletions Deployer/Ssh.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace BeSimple\DeploymentBundle\Deployer;

use Sensio\Bundle\GeneratorBundle\Command\Helper\DialogHelper;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use BeSimple\DeploymentBundle\Event\CommandEvent;
use BeSimple\DeploymentBundle\Event\FeedbackEvent;
Expand Down Expand Up @@ -96,16 +98,13 @@ public function getStderr($glue = "\n")
public function run(array $connection, array $commands, $real = false)
{
$this->connect($connection);
$this->execute(array('type' => 'shell', 'command' => sprintf('cd %s', $connection['path'])));

if ($real) {
foreach ($commands as $command) {
$this->execute($command);
if($real){
foreach($commands as $command){
$this->execute($command, $connection);
}
}

$this->disconnect();

return $this->stdout;
}

Expand All @@ -116,48 +115,54 @@ public function run(array $connection, array $commands, $real = false)
*/
protected function connect(array $connection)
{
$this->session = ssh2_connect($connection['host'], $connection['ssh_port']);
$methods = @$connection['connect_methods'] ?: @$this->config['connect_methods'];

$this->session = @ssh2_connect($connection['host'], $connection['ssh_port'], $methods);
if (!$this->session) {
throw new \InvalidArgumentException(sprintf('SSH connection failed on "%s:%s"', $connection['host'], $connection['ssh_port']));
}

if (isset($connection['username']) && isset($connection['pubkey_file']) && isset($connection['privkey_file'])) {
if (!ssh2_auth_pubkey_file($connection['username'], $connection['pubkey_file'], $connection['privkey_file'], $connection['passphrase'])) {
throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s" with public key "%s"', $connection['username'], $connection['pubkey_file']));
$username = @$connection['username'] ?: @$this->config['username'];
$password = @$connection['password'] ?: @$this->config['password'];

if($username && $password){
if(!ssh2_auth_password($this->session, $username, $password)){
throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s"', $username));
}
} else if ($connection['username'] && $connection['password']) {
if (!ssh2_auth_password($this->session, $connection['username'], $connection['password'])) {
throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s"', $connection['username']));
}elseif($username){
$pubkey = @$connection['pubkey_file'] ?: @$this->config['pubkey_file'];
$privkey = @$connection['privkey_file'] ?: @$this->config['privkey_file'];
$passphrase = @$connection['passphrase'] ?: @$this->config['passphrase'];

$co = new ConsoleOutput();
$helper = new DialogHelper();
$helper->setInputStream($this->stdin);
if(!$pubkey){
$pubkey = $helper->ask($co,'pubkey_file?');
}
if(!$privkey){
$privkey = $helper->ask($co,'privkey_file?');
}
if(!$passphrase){
$passphrase = $helper->askHiddenResponse($co,'passphrase?');
}
}

$this->shell = ssh2_shell($this->session);

if (!$this->shell) {
throw new \RuntimeException(sprintf('Failed opening "%s" shell', $this->config['shell']));
if(!ssh2_auth_pubkey_file($this->session, $username, $pubkey, $privkey, $passphrase)){
throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s" with public key "%s"', $username, $pubkey));
}
}

$this->stdout = array();
$this->stdin = array();
}

/**
* @return void
*/
protected function disconnect()
{
fclose($this->shell);
}

/**
* @param array $command
* @return void
* @param array $commandArray
* @param array $connection
*/
protected function execute(array $command)
protected function execute(array $commandArray, array $connection)
{
$command = $this->buildCommand($command);

$command = $this->buildCommand($commandArray, $connection);
$this->dispatcher->dispatch(Events::onDeploymentSshStart, new CommandEvent($command));

$outStream = ssh2_exec($this->session, $command);
Expand All @@ -166,22 +171,18 @@ protected function execute(array $command)
stream_set_blocking($outStream, true);
stream_set_blocking($errStream, true);

$stdout = explode("\n", stream_get_contents($outStream));
$stderr = explode("\n", stream_get_contents($errStream));
$stdout = stream_get_contents($outStream);
$stderr = stream_get_contents($errStream);

if (count($stdout)) {
$this->dispatcher->dispatch(Events::onDeploymentRsyncFeedback, new FeedbackEvent('out', implode("\n", $stdout)));
if($stdout){
$this->dispatcher->dispatch(Events::onDeploymentSshFeedback, new FeedbackEvent('out', $stdout));
}

if (count($stdout)) {
$this->dispatcher->dispatch(Events::onDeploymentRsyncFeedback, new FeedbackEvent('err', implode("\n", $stderr)));
if($stderr){
$this->dispatcher->dispatch(Events::onDeploymentSshFeedback, new FeedbackEvent('err', $stderr));
}

$this->stdout = array_merge($this->stdout, $stdout);

if (is_array($stderr)) {
$this->stderr = array_merge($this->stderr, $stderr);
} else {
if(!$stderr){
$this->dispatcher->dispatch(Events::onDeploymentSshSuccess, new CommandEvent($command));
}

Expand All @@ -190,18 +191,27 @@ protected function execute(array $command)
}

/**
* @param array $command
* @param array $commandArray
* @param array $connection
* @return string
* @throws \InvalidArgumentException
*/
protected function buildCommand(array $command)
protected function buildCommand(array $commandArray, array $connection)
{
if ($command['type'] === 'shell') {
return $command['command'];
$envs = '';
foreach($commandArray['env'] as $key => $value){
$envs .= 'declare -x '.$key.'='.$value.' && ';
}

$symfony = $this->config['symfony_command'];
$env = $command['env'] ?: $this->env;
switch($commandArray['type']){
case 'shell':
return sprintf("%s%s", $envs, $commandArray['command']);
break;
case 'symfony':
return sprintf('%scd %s && %s %s', $envs, $connection['path'], $connection['symfony_command'], $commandArray['command']);
break;
}

return sprintf('%s %s --env="%s"', $symfony, $command['command'], $env);
throw new \InvalidArgumentException(sprintf('CommandType "%s" invalid', $commandArray['type']));
}
}
Loading