proxmox_cloud-init.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <?php
  2. /**
  3. * cloudinit script for pfSense on Proxmox VE
  4. *
  5. * The script does a pfSense configuration in that manner:
  6. * 1. looks for an available cloudinit drive and mount it to /etc/cloudinit
  7. * 2. compares the cloudinit files on the cloudinit drive by a local copy placed in /etc/cloudinit
  8. * and ends without changing anything if the files on both location are similar
  9. * 3. parses the cloudinit YAML files and prepare and set the given values to pfSense config array
  10. * 4. write the pfSense configuration and reboot the instance
  11. * HowTo install:
  12. * 1. get a copy of the YAML parse from https://github.com/mustangostang/spyc/ and place it to /usr/local/sbin
  13. * 2. place a copy of proxmox_cloudinit.php also to /usr/local/sbin
  14. * HowTo use:
  15. * 1. attach a cloudinit drive to the pfSense VM
  16. * 2. create a startupscript
  17. *
  18. * @version 0.9
  19. * @author Andre Genrich andre.genrich@thurdata.ch
  20. */
  21. require_once('Spyc.php'); // yaml parser
  22. require_once('config.inc'); // pfSense configuration structures
  23. require_once('system.inc'); // pfSense system utilities
  24. static $cloudInitFiles = array('meta-data', 'network-config', 'user-data'); // provided by Proxmox
  25. // tuneables
  26. static $cloudInitLocalPath = '/etc/cloud'; // place for $cloudInitControlFile, $cloudInitResetRequest and a local copy of $cloudInitFiles
  27. static $cloudInitMountPoint = '/mnt/cloud'; // mountpoint for cloudinit drive
  28. static $cloudInitControl = 'lastrun'; // file contains the timestamp of the last run or "init" after a change run
  29. static $cloudInitResetControl = 'emergency'; // file contains the timestamp of the last emergency run
  30. static $unstableRunTimeout = 300; // after $unstableRunTimeout the script assumes the system is stable
  31. /**
  32. * calcCIDR calculates a netmask in CIDR notation from dotted decimal notation
  33. *
  34. * @param string $mac netmask in dotted decimal notation
  35. * @return int $cidr netmask in CIDR notation
  36. */
  37. function calcCIDR( $mac) {
  38. $cidr = 32 - log((ip2long($mac) ^ ip2long('255.255.255.255')) + 1 ,2);
  39. return $cidr;
  40. }
  41. /**
  42. * createDir creates necessary directories
  43. *
  44. * @param string $path is the full path of the directory
  45. */
  46. function createDir( $path) {
  47. if (!is_dir("$path")) {
  48. if (!mkdir ( "$path", 0770, TRUE)) {
  49. $sys_err= error_get_last();
  50. syslog(LOG_ERR,"cloudinit: failed to create $path, error $sys_err[type] $sys_err[message]");
  51. exit(1);
  52. }
  53. }
  54. }
  55. /**
  56. * restoreConfiguration removes all local cloudinit files and starts a reset to factory defaults
  57. */
  58. function restoreConfiguration() {
  59. unlink("$cloudInitLocalPath/$cloudInitControl");
  60. unlink("$cloudInitLocalPath/$cloudInitResetControl");
  61. foreach ( $cloudInitFiles as $cloudInitFile) {
  62. unlink("$cloudInitLocalPath/$cloudInitFile");
  63. }
  64. reset_factory_defaults();
  65. system_reboot_sync();
  66. }
  67. /**
  68. * controlEmergencyRun check and update run control files
  69. *
  70. * $cloudInitControl contains "init" after a change run -> controlEmergencyRun outs the ciúrrent timestamp into $cloudInitControl
  71. *
  72. * @return int 0 to trigger a skip run
  73. * @return int 1 to trigger an emergency run (set again all cloudinit settings)
  74. * @return int 3 to trigger a reset to factory defaults run (reset all cloudinit & pfSense changes)
  75. */
  76. function controlEmergencyRun() {
  77. if ((file_get_contents( "$cloudInitLocalPath/$cloudInitControl")) == "init") {
  78. file_put_contents( "$cloudInitLocalPath/$cloudInitControl", time());
  79. return 0;
  80. }
  81. if ((file_get_contents( "$cloudInitLocalPath/$cloudInitControl") + 300) > time()) {
  82. if (file_exists( "$cloudInitLocalPath/$cloudInitResetControl")) {
  83. if ((file_get_contents( "$cloudInitLocalPath/$cloudInitResetControl") + 300) > time()) {
  84. unlink( "$cloudInitLocalPath/$cloudInitResetControl");
  85. return 2;
  86. } else {
  87. unlink( "$cloudInitLocalPath/$cloudInitResetControl");
  88. return 1;
  89. }
  90. } else {
  91. file_put_contents( "$cloudInitLocalPath/$cloudInitResetControl", time());
  92. return 1;
  93. }
  94. } else {
  95. unlink( "$cloudInitLocalPath/$cloudInitResetControl");
  96. file_put_contents( "$cloudInitLocalPath/$cloudInitControl", time());
  97. return 0;
  98. }
  99. }
  100. /**
  101. * updateCloudInitFiles compares the cloudinit files
  102. *
  103. * conpares the cloudinit drive by a local copy and
  104. * update the local copy in case of changes
  105. * or if the local copy does not exist
  106. *
  107. * @return bool true in case of updates, false in case of all is up to date
  108. */
  109. function updateCloudInitFiles() {
  110. $cloudInitFileDiff = false;
  111. // check for updated config files and update the local copy in case of differs
  112. foreach ( $cloudInitFiles as $cloudInitFile ) {
  113. if (!((sha1_file("$cloudInitLocalPath/$cloudInitFile")) == (sha1_file("$cloudInitMountPoint/$cloudInitFile")))) {
  114. if (!copy("$cloudInitMountPoint/$cloudInitFile", "$cloudInitLocalPath/$cloudInitFile")) {
  115. $sys_err = error_get_last();
  116. syslog(LOG_ERR,"cloudinit failed: $sys_err[type] $sys_err[message]");
  117. exit(1);
  118. } else {
  119. $cloudInitFileDiff = true;
  120. }
  121. }
  122. }
  123. return $cloudInitFileDiff;
  124. }
  125. /**
  126. * checkCloudInitFiles probes existence of all necessary cloudinit files
  127. *
  128. * @return bool true in case of all files are in place or false if something missing
  129. */
  130. function checkCloudInitFiles() {
  131. foreach($cloudInitFiles as $cloudInitFile) {
  132. if (!file_exists("$cloudInitPath/$cloudInitFile")) {
  133. return false;
  134. }
  135. }
  136. return true;
  137. }
  138. /**
  139. * checkCloudInitDevice search for a cloudinit drive
  140. *
  141. * probes any attached cd device for existing cloudinit files
  142. * mounts the drive to /mnt/cloudinit and probes that all neccessary cloudinit files exist
  143. *
  144. * @return bool true in case of success, fals in case of no cloudinit drive could found
  145. */
  146. function checkCloudInitDevice() {
  147. // get attached cd devices
  148. preg_match_all( "/.*cd[0-9] /", file_get_contents('/var/run/dmesg.boot'), $cdDeviceList);
  149. if (empty($cdDeviceList[0])) {
  150. syslog(LOG_ERR,"cloudinit failed: No cloudinit drive found");
  151. exit(1);
  152. }
  153. // check cloudinit iso is mounted or try to mount the cloudinit medium
  154. foreach($cdDeviceList[0] as $cdDevice) {
  155. // is a cd mounted on /mnt/cloudinit ?
  156. $sys_err_msg = exec("df $cloudInitMountPoint | grep -q /dev/$cdDevice 2>&1", $sys_msg, $sys_err_no);
  157. if ($sys_err_no) { // not mounted
  158. // try to mount the cd
  159. $mount_err = exec("mount_cd9660 /dev/$cdDevice $cloudInitMountPoint", $sys_msg, $sys_err_no);
  160. if (!$sys_err_no) {
  161. if (checkCloudInitFiles( $cloudInitFiles, $cloudInitMountPoint)) {
  162. syslog(LOG_INFO,"cloudinit: found cloud init drive on $cdDevice mounted at $cloudInitMountPoint/");
  163. return true;
  164. } else {
  165. $umount_err = exec("umount $cloudInitMountPoint", $sys_msg, $sys_err_no);
  166. if ($sys_err_no) {
  167. syslog(LOG_ERR,"cloudinit: mounted a wrong device $cdDevice but not able to umount because $sys_msg");
  168. return false;
  169. }
  170. }
  171. }
  172. } else { //already mounted (but not by us)
  173. if (checkCloudInitFiles( $cloudInitFiles, $cloudInitMountPoint)) {
  174. syslog(LOG_INFO,"cloudinit: found cloud init drive on $cdDevice at $cloudInitMountPoint/");
  175. return true;
  176. } else {
  177. syslog(LOG_ERR,"cloudinit: expected files on cloud init drive not found");
  178. return false;
  179. }
  180. }
  181. }
  182. return false;
  183. }
  184. /**
  185. * searchIfDevice does a case insensitive search for a network device by given hardware address
  186. *
  187. * @param string $mac hardware address
  188. * @return string $if[1] device name or false if no device could be found
  189. */
  190. function searchIfDevice( $mac) {
  191. exec("ifconfig -a | awk '/^[a-z]/ { gsub(/\:/,\"\", $1); iface=$1; next } /hwaddr/ { mac=$2; print mac, iface}'", $ifMacList, $sys_err_no);
  192. foreach($ifMacList as $ifMac) {
  193. $if = explode(" ",$ifMac);
  194. if (strcasecmp("$if[0]", "$mac") == 0) { // case insensitive
  195. return $if[1];
  196. }
  197. }
  198. return false;
  199. }
  200. // create mountpoint for cloudinit drive if not exist
  201. createDir( $cloudInitMountPoint);
  202. // create local folder for config & control files
  203. createDir( $cloudInitLocalPath);
  204. // search and mount the cloudinit image or exit 1
  205. if (!checkCloudInitDevice()) {
  206. syslog(LOG_ERR,"cloudinit: no cloud init drive available, skipping...\n");
  207. exit(1);
  208. }
  209. // probe for special run modes
  210. if (!updateCloudInitFiles()) {
  211. switch (controlEmergencyRun()) {
  212. case 0:
  213. syslog(LOG_INFO,"cloudinit: cloud init files up to date, skipping...\n");
  214. exit(0);
  215. break;
  216. case 1:
  217. syslog(LOG_INFO,"cloudinit: cloud init files up to date, but emergency run triggered...\n");
  218. break;
  219. case 2:
  220. syslog(LOG_INFO,"cloudinit: reset run triggered, restore cloudinit default configuration!\n");
  221. restoreConfiguration();
  222. break;
  223. }
  224. }
  225. // parse cloud init configurations
  226. // $metaData = Spyc::YAMLLoad("$cloudInitLocalPath/$cloudInitFiles[0]"); // meta-data (actually not in use)
  227. $netData = Spyc::YAMLLoad("$cloudInitLocalPath/$cloudInitFiles[1]"); // network-config
  228. $userData = Spyc::YAMLLoad("$cloudInitLocalPath/$cloudInitFiles[2]"); // user-data
  229. // configure nameserver if set
  230. $ifLastNr=(count($netData['config'])-1); // the YAML parser reurns a crappy array like this
  231. if (reset($netData['config'][$ifLastNr]) == 'nameserver') { // (
  232. next($netData['config'][$ifLastNr]); // [type] => nameserver
  233. $dnsServerCount = 0; // [address] =>
  234. while($nameserverIP=next($netData['config'][$ifLastNr])) { // [0] => 1.2.3.4
  235. $config['system']['dnsserver'][$dnsServerCount] = $nameserverIP; // [1] => 4.3.2.1
  236. $dnsServerCount++; // [search] =>
  237. } // [2] => mydomain.local
  238. $config['system']['domain'] = next($netData['config'][$ifLastNr]); // )
  239. }
  240. // configure WAN interface
  241. $wanDevice = searchIfDevice( $netData['config'][0]['mac_address']);
  242. if (!$wanDevice) {
  243. syslog(LOG_ERR,"cloudinit: no WAN device found");
  244. exit(1);
  245. } else {
  246. $config['interfaces']['wan']['if'] = $wanDevice;
  247. }
  248. if ($netData['config'][0][0]['type'] == 'static') {
  249. $config['interfaces']['wan']['ipaddr'] = $netData['config'][0][0]['address'];
  250. $config['interfaces']['wan']['subnet'] = calcCIDR( $netData['config'][0][0]['netmask']);
  251. $config['interfaces']['wan']['gateway'] = $netData['config'][0][0]['gateway'];
  252. }
  253. // configure primary LAN device
  254. $lanDevice = searchIfDevice( $netData['config'][1]['mac_address']);
  255. if (!$lanDevice) {
  256. syslog(LOG_ERR,"cloudinit: no LAN device found");
  257. exit(1);
  258. } else {
  259. $config['interfaces']['lan']['if'] = $lanDevice;
  260. }
  261. if ($netData['config'][1][0]['type'] == 'static') {
  262. $config['interfaces']['lan']['ipaddr'] = $netData['config'][1][0]['address'];
  263. $config['interfaces']['lan']['subnet'] = calcCIDR( $netData['config'][1][0]['netmask']);
  264. $config['interfaces']['lan']['gateway'] = $netData['config'][1][0]['gateway'];
  265. }
  266. // configure additional network devices
  267. if ($ifLastNr > 2) {
  268. for ($ifNr=2;$ifNr<$ifLastNr;$ifNr++) {
  269. $optDeviceName = "opt" . strval($ifNr-1);
  270. $optDevice = searchIfDevice( $netData['config'][$ifNr]['mac_address']);
  271. if (!$optDevice) {
  272. syslog(LOG_WARN,"cloudinit: given network device {$netData['config'][$ifNr]['mac_address']} not found");
  273. break;
  274. } else {
  275. $config['interfaces'][$optDeviceName]['if'] = $optDevice;
  276. }
  277. if ($netData['config'][$ifNr][0]['type'] == 'static') {
  278. $config['interfaces'][$optDeviceName]['ipaddr'] = $netData['config'][$ifNr][0]['address'];
  279. $config['interfaces'][$optDeviceName]['subnet'] = calcCIDR( $netData['config'][$ifNr][0]['netmask']);
  280. $config['interfaces'][$optDeviceName]['gateway'] = $netData['config'][$ifNr][0]['gateway'];
  281. }
  282. }
  283. }
  284. // add ssh keys
  285. if (isset($userData['ssh_authorized_keys'])) {
  286. foreach ($userData[ssh_authorized_keys] as $sshKey) {
  287. $sshKeys .= "$sshKey\n";
  288. }
  289. $config['system']['user'][0]['authorizedkeys'] = base64_encode("$sshKeys");
  290. }
  291. $config['system']['hostname'] = $userData['hostname'];
  292. $config['system']['user'][0]['bcrypt-hash'] = $userData['password'];
  293. // write the configuration
  294. write_config();
  295. // update runmode control file
  296. file_put_contents( "$cloudInitLocalPath/$cloudInitControl", "init");
  297. // skip pfSense wizard
  298. unlink("/conf/trigger_initial_wizard");
  299. // finally reboot the system
  300. system_reboot_sync();