FetchJob::runCommand()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 9.2
cc 4
eloc 11
nc 8
nop 2
1
<?php
2
3
class FetchJob extends DeploynautJob {
4
5
	public $args;
6
7
	/**
8
	 * @var DNProject
9
	 */
10
	protected $project;
11
12
	/**
13
	 * @var \DeploynautLogFile
14
	 */
15
	protected $log;
16
17
	/**
18
	 * @var string
19
	 */
20
	protected $user;
21
22
	/**
23
	 * @global array $databaseConfig
24
	 */
25
	public function setUp() {
26
		global $databaseConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
27
		DB::connect($databaseConfig);
28
29
		$this->updateStatus('Started');
30
		chdir(BASE_PATH);
31
	}
32
33
	public function perform() {
34
		set_time_limit(0);
35
36
		if(!empty($this->args['logfile'])) {
37
			$this->log = new DeploynautLogFile($this->args['logfile']);
38
		}
39
40
		$this->project = DNProject::get()->byId($this->args['projectID']);
41
		if(!($this->project && $this->project->exists())) {
42
			throw new RuntimeException(sprintf('Project ID %s not found', $this->args['projectID']));
43
		}
44
45
		$this->user = DNData::inst()->getGitUser() ?: null;
46
47
		// Disallow concurrent git fetches on the same project.
48
		// Only consider fetches started in the last 30 minutes (older jobs probably got stuck)
49
		try {
50
			if(!empty($this->args['fetchID'])) {
51
				$runningFetches = DNGitFetch::get()
52
					->filter(array(
53
						'ProjectID' => $this->project->ID,
54
						'Status' => array('Queued', 'Started'),
55
						'Created:GreaterThan' => strtotime('-30 minutes')
56
					))
57
					->exclude('ID', $this->args['fetchID']);
58
59
				if($runningFetches->count()) {
60
					$runningFetch = $runningFetches->first();
61
					$message = sprintf(
62
						'Another fetch is in progress (started at %s by %s)',
63
						$runningFetch->dbObject('Created')->Nice(),
64
						$runningFetch->Deployer()->Title
65
					);
66
					if($this->log) {
67
						$this->log->write($message);
68
					}
69
					throw new RuntimeException($message);
70
				}
71
			}
72
73
			// Decide whether we need to just update what we already have
74
			// or initiate a clone if no local repo exists.
75
			if($this->project->repoExists() && empty($this->args['forceClone'])) {
0 ignored issues
show
Bug introduced by
The method repoExists() does not exist on DataObject. Did you maybe mean exists()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
76
				$this->fetchRepo();
77
			} else {
78
				$this->cloneRepo();
79
			}
80
		} catch(Exception $e) {
81
			if($this->log) {
82
				$this->log->write($e->getMessage());
83
			}
84
			throw $e;
85
		}
86
		$this->project->clearGitCache();
87
		$this->updateStatus('Finished');
88
	}
89
90
	protected function fetchRepo() {
91
		$this->runCommand(
92
			'/usr/bin/git fetch -p origin +refs/heads/*:refs/heads/* --tags',
93
			$this->project->getLocalCVSPath()
94
		);
95
	}
96
97
	protected function cloneRepo() {
98
		if(file_exists($this->project->getLocalCVSPath())) {
99
			$this->runCommand(sprintf(
100
				'rm -rf %s',
101
				escapeshellarg($this->project->getLocalCVSPath())
102
			));
103
		}
104
105
		$this->runCommand(sprintf(
106
			'/usr/bin/git clone --bare -q %s %s',
107
			escapeshellarg($this->project->CVSPath),
108
			escapeshellarg($this->project->getLocalCVSPath())
109
		));
110
	}
111
112
	/**
113
	 * Run a shell command.
114
	 *
115
	 * @param string $command The command to run
116
	 * @param string|null $workingDir The working dir to run command in
117
	 * @throws RuntimeException
118
	 */
119
	protected function runCommand($command, $workingDir = null) {
120
		if(!empty($this->user)) {
121
			$command = sprintf('sudo -u %s %s', $this->user, $command);
122
		}
123
		if($this->log) {
124
			$this->log->write(sprintf('Running command: %s', $command));
125
		}
126
		$process = new AbortableProcess($command, $workingDir);
127
		$process->setEnv($this->project->getProcessEnv());
128
		$process->setTimeout(1800);
129
		$process->run();
130
		if(!$process->isSuccessful()) {
131
			throw new RuntimeException($process->getErrorOutput());
132
		}
133
	}
134
135
	/**
136
	 * @param string $status
137
	 * @global array $databaseConfig
138
	 */
139
	protected function updateStatus($status) {
140
		global $databaseConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
141
		DB::connect($databaseConfig);
142
143
		if(!empty($this->args['fetchID'])) {
144
			$fetch = DNGitFetch::get()->byID($this->args['fetchID']);
145
			if($fetch && $fetch->exists()) {
146
				$fetch->Status = $status;
147
				$fetch->write();
148
			}
149
		}
150
	}
151
152
}
153