Merge branch 'maintenance-0.20.x' into yandex-prod
[racktables] / scripts / syncdomain.php
1 #!/usr/bin/env php
2 <?php
3
4 # This file is a part of RackTables, a datacenter and server room management
5 # framework. See accompanying file "COPYING" for the full copyright and
6 # licensing information.
7
8 $script_mode = TRUE;
9 require 'inc/init.php';
10
11 function usage ($rc)
12 {
13 echo "Usage: <this file> <options>\n";
14 echo "\t\t--vdid=<VLAN domain ID>\n";
15 echo "\t\t--mode=pull\n";
16 echo "\t\t--mode=pullall\n";
17 echo "\t\t--mode=push\n";
18 echo "\t\t[--max=<max_to_do>]\n";
19 echo "\t\t[--verbose]\n";
20 echo "\t\t[--nolock]\n";
21 echo "\t\t[--stderr]\n";
22 echo "\t\t--help\n";
23 exit ($rc);
24 }
25
26 define ('PML_VERBOSE', 1 << 0); // display message only if --verbose option specified
27 define ('PML_NOTICE', 1 << 1); // the message is informational, do not write to STDERR
28 function print_message_line($text, $flags = 0)
29 {
30 global $options;
31 if (! array_key_exists ('verbose', $options) and $flags & PML_VERBOSE)
32 return;
33 $buff = date (DATE_RFC1123) . ": ${text}\n";
34 echo $buff;
35 if (array_key_exists ('stderr', $options) and ! ($flags & PML_NOTICE))
36 fwrite (STDERR, $buff);
37 }
38
39 $options = getopt ('', array ('vdid:', 'max::', 'mode:', 'verbose', 'nolock', 'stderr', 'help'));
40 if (array_key_exists ('help', $options))
41 usage (0);
42 if (!array_key_exists ('mode', $options))
43 usage (1);
44
45 switch ($options['mode'])
46 {
47 case 'pullall':
48 $do_push = FALSE;
49 break;
50 case 'pull':
51 $do_push = FALSE;
52 break;
53 case 'push':
54 $do_push = TRUE;
55 break;
56 default:
57 usage (1);
58 }
59
60 $max = array_fetch ($options, 'max', 0);
61 $nolock = array_key_exists ('nolock', $options);
62
63 $todo = array
64 (
65 'pull' => array ('sync_ready', 'resync_ready'),
66 'push' => array ('sync_ready', 'resync_ready'),
67 'pullall' => array ('sync_ready', 'resync_ready', 'sync_aging', 'resync_aging', 'done'),
68 );
69
70 if (! $nolock)
71 {
72 $domain_key = isset ($options['vdid']) ? $options['vdid'] : 0;
73 $filename = '/var/tmp/RackTables-syncdomain-' . $domain_key . '.pid';
74 if (FALSE === $fp = @fopen ($filename, 'c+'))
75 {
76 print_message_line ("Failed to open ${filename}");
77 exit (1);
78 }
79 $wouldblock = 0;
80 if (! flock ($fp, LOCK_EX|LOCK_NB, $wouldblock) || $wouldblock)
81 {
82 $current_time = time();
83 $stat = fstat ($fp);
84 if (! isset ($stat['mtime']))
85 {
86 print_message_line ("Failed to obtain mtime of ${filename}");
87 exit (1);
88 }
89 $pidfile_mtime = $stat['mtime'];
90 if ($current_time < $pidfile_mtime)
91 {
92 print_message_line ("Warning: pidfile ${filename} mtime is in future!");
93 exit (1);
94 }
95 // don't indicate failure unless the pidfile is 15 minutes or more old
96 if ($current_time < $pidfile_mtime + 15 * 60)
97 exit (0);
98 print_message_line ("Failed to lock ${filename}, already locked by PID " . trim (fgets ($fp, 10)));
99 exit (1);
100 }
101
102 ftruncate ($fp, 0);
103 fwrite ($fp, getmypid() . "\n");
104 // don't close $fp yet: we need to keep an flock
105 }
106
107 // fetch all the needed data from DB (preparing for DB connection loss)
108 $vswitch_filter = array();
109 if (isset ($options['vdid']))
110 $vswitch_filter['domain_id'] = $options['vdid'];
111 $switch_list = getVLANSwitchInfoRows ($vswitch_filter);
112 $enabled_switches = listConstraint ('object', 'SYNC_802Q_LISTSRC');
113
114 $switch_queue = array();
115 foreach ($switch_list as $vswitch)
116 {
117 $object_id = $vswitch['object_id'];
118 $new_disabled = ! isset ($enabled_switches[$object_id]);
119 $queue = detectVLANSwitchQueue ($vswitch);
120 if ($queue != 'disabled' && $new_disabled)
121 {
122 setVLANSwitchError ($object_id, E_8021Q_SYNC_DISABLED);
123 continue;
124 }
125 elseif ($queue == 'disabled' && ! $new_disabled)
126 {
127 $vswitch['last_errno'] = E_8021Q_NOERROR;
128 setVLANSwitchError ($object_id, $vswitch['last_errno']);
129 $queue = detectVLANSwitchQueue ($vswitch);
130 }
131
132 if (in_array ($queue, $todo[$options['mode']]))
133 $switch_queue[] = spotEntity ('object', $object_id);
134 }
135
136 // YOU SHOULD NOT USE DB FUNCTIONS BELOW IN THE PARENT PROCESS
137 // THE PARENT'S DB CONNECTION IS LOST DUE TO RECONNECTING IN THE CHILD
138 $fork_slots = getConfigVar ('SYNCDOMAIN_MAX_PROCESSES');
139 $do_fork = ($fork_slots > 1) and extension_loaded ('pcntl');
140 if ($fork_slots > 1 and ! $do_fork)
141 throw new RackTablesError ('PHP extension \'pcntl\' not found, can not use childs', RackTablesError::MISCONFIGURED);
142 $switches_working = 0;
143 $switchesdone = 0;
144 foreach ($switch_queue as $object)
145 {
146 if ($do_fork)
147 {
148 // wait for the next free slot
149 while ($fork_slots <= $switches_working)
150 {
151 pcntl_waitpid (-1, $wait_status);
152 --$switches_working;
153 }
154 $i_am_child = (0 === $fork_res = pcntl_fork());
155 }
156 if (! $do_fork || $i_am_child)
157 {
158 try
159 {
160 // make a separate DB connection for correct concurrent transactions handling
161 if ($i_am_child)
162 connectDB();
163 $portsdone = exec8021QDeploy ($object['id'], $do_push);
164 $flags = PML_NOTICE;
165 if (! $portsdone)
166 $flags |= PML_VERBOSE;
167 print_message_line ("Done '${object['dname']}': ${portsdone}", $flags);
168 }
169 catch (RackTablesError $e)
170 {
171 print_message_line ("FAILED '${object['dname']}': " . $e->getMessage());
172 }
173 if ($i_am_child)
174 exit (0);
175 }
176 if (isset ($fork_res) and $fork_res > 0)
177 ++$switches_working;
178
179 if (++$switchesdone == $max)
180 {
181 print_message_line ("Maximum of ${max} items reached, terminating", PML_NOTICE|PML_VERBOSE);
182 break;
183 }
184 }
185
186 // wait for all childs to exit
187 while ($switches_working > 0)
188 {
189 --$switches_working;
190 pcntl_waitpid (-1, $wait_status);
191 }
192
193 if (! $nolock)
194 {
195 flock ($fp, LOCK_UN); // explicitly unlock file as PHP 5.3.2 made it mandatory
196 if (FALSE === unlink ($filename))
197 {
198 print_message_line ("Failed removing pidfile ${filename}");
199 exit (1);
200 }
201 }
202 exit (0);
203 ?>