Все записи автора Sepuka

Работа с удаленными ФС

Иногда нужно смонтировать удаленную файловую систему, например, я разрабатываю ПО которое организовано в виде deb-пакета, причем делаю я это на rpm-based машине, т.е. устанавливать такой пакет будет затруднительно для тестирования. Можно исходные данные поместить на тестовый сервер и править текст на своем любимом редакторе на локальной машине. Пример:

1
sshfs -p 8022 shlomin@127.0.0.1:/home/user/vcard /home/user/server.gates/
sshfs -p 8022 shlomin@127.0.0.1:/home/user/vcard /home/user/server.gates/

Это вообще говоря довольно простой и известный способ, но я хотел указать на то, что специально указал порт 8022, чтобы показать что тот сервер который я хочу юзать находится во внутренней сети доступ к которую есть через третий сервер, а этот самый третий сервер я предварительно проксирую через ssh, например так:

1
sudo ssh -L 8022:192.168.77.80:22 user@server
sudo ssh -L 8022:192.168.77.80:22 user@server

получается ssh слушает 8022 и проксирует трафик через третий сервер на целевую машину 192.168.77.80 уже на 22 порт. Чтобы размонтировать ресурс, достаточно выполнить команду

1
fusermount -u /home/user/server.gates/
fusermount -u /home/user/server.gates/

где /home/user/server.gates/ есть точка монтирования.

getAllKeys в memcache

Не все расширения могут позволить работать с со всеми возможностями memcached, а некоторые функции работают неоптимально, например, getAllKeys выполняет запрос
stats cachedump N 0 200 раз (!). Я же предлагаю уйти от метода тотального перебора и спросить у сервера в каких точно slab он хранит данные. Для этого существует запрос stats items , привожу пример функции для кастомных запросов

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getDataFromMemcached($command) {
  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if ($socket === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_connect($socket, memcached_host, memcached_port) === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_write($socket, "$command\n") === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  $answer = "";
  while ($out = socket_read($socket, 1024, PHP_BINARY_READ)) {
    $answer .= $out;
    if (strlen($out) < 1024)
      break;
  }
  socket_close($socket);
  return $answer;
}
function getDataFromMemcached($command) {
  $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if ($socket === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_connect($socket, memcached_host, memcached_port) === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  if (socket_write($socket, "$command\n") === FALSE)
    throw new Exception(socket_strerror(socket_last_error()));
  $answer = "";
  while ($out = socket_read($socket, 1024, PHP_BINARY_READ)) {
    $answer .= $out;
    if (strlen($out) < 1024)
      break;
  }
  socket_close($socket);
  return $answer;
}

Вот допустим есть такая функция которая шлет запросы на сервер, теперь следует спросить у сервера Теперь следует спросить у сервера stats items, он скажет что-то вроде

................
STAT items:16:expired_unfetched 0
STAT items:16:evicted_unfetched 0
STAT items:17:number 4
STAT items:17:age 492
................

и становится понятно какие stab заняты. Затем извлечь идентификаторы slabs (это циферки 16,17…) и сделать запрос stats cachedump {$slab} 0 который вернет что нам нужно

ITEM b0d35f99c68e54c47a0839f5b4f91a73 [718 b; 1384951681 s]

потом остается только сделать get КЛЮЧ для получения значения. Пример выложен на гитхаб

Расчет выражения

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
define('FORMULA', '1+(1+1)*(1+1)/1+1-1+(1+1*1)-(1-(2-3-(4-5)))+1');
 
echo 'RESULT=' . p(FORMULA);
 
function p($expr, $offset=0) {
  $operands = array();
  while ($offset < strlen($expr)) {
    if (count($operands) == 3) {
      $operands = proccess($operands);
    }
 
  if (isComplex($expr[$offset])) {
    ++$offset;// Отрезаю первую скобку выражения
    $complexVar = p($expr, &$offset);
    $operands[] = array((int)$complexVar, $expr[$offset]);
    if (strlen($expr) > $offset + 1 && ! isEnd($expr[$offset]))
      ++$offset;
    } elseif (isEnd($expr[$offset])) {
      // должно быть два элемента
      $left = array_shift($operands);
      $center = array_shift($operands);
      $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
      ++$offset;// Переходим к следующему сиволу после закрывающей скобки
      break;
    } elseif (preg_match('/(d)+/', $expr, $matches, 0, $offset)) {
      if (count($matches) > 1) {
        $operationPos = $offset + strlen($matches[1]);// Позиция операции=текущее смещение + длина
        if (($operationPos >= strlen($expr)) || isEnd($expr[$operationPos])) {// Конец выражения или строки
          if (count($operands) == 2) {
            $operands[] = array($matches[1], (strlen($expr) < $operationPos) ? $expr[$operationPos] : '');
            $operands = proccess($operands);
            $result = eval("return {$operands[0][0]} {$operands[0][1]} {$operands[1][0]};");
            if ($operationPos + 1 < strlen($expr))
              $offset = $operationPos + 1;
            break;
    } else {
      $result = eval("return {$operands[0][0]} {$operands[0][1]} {$matches[1][0]};");
      if ($operationPos + 1 < strlen($expr))
        $offset = $operationPos + 1;
      break;
    }
    } else {
  $operands[] = array((int)$matches[1], substr($expr, $operationPos, 1));
  // Сейчас позиция операции указывает на закрывающую скобку, двигаемся дальше
  if (strlen($expr) > $operationPos + 1)
    $offset = $operationPos + 1;
  }
    } else
      throw new Exception('?');
    } else {
      throw new Exception('?');
    }
  }
 
  return $result;
}
 
/*
* Из трех операндов делает два
*/
function proccess($operands) {
  if (in_array($operands[0][1], array('+', '-')) &&   (in_array($operands[1][1], array('*', '/')))) {
    // Центральный с правым
    $right = array_pop($operands);
    $center = array_pop($operands);
    echo "processing CR {$center[0]} {$center[1]} {$right[0]};n";
    $result = eval("return {$center[0]} {$center[1]} {$right[0]};");
    array_push($operands, array($result, $right[1]));
  } else {
    $left = array_shift($operands);
    $center = array_shift($operands);
    $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
    echo "processing LC {$left[0]} {$left[1]} {$center[0]}=$result;n";
    array_unshift($operands, array((int)$result, $center[1]));
  }
  return $operands;
}
 
function isComplex($symbol) {
  return ($symbol == '(') ? TRUE : FALSE;
}
 
function isEnd($symbol) {
  return ($symbol == ')') ? TRUE : FALSE;
}
define('FORMULA', '1+(1+1)*(1+1)/1+1-1+(1+1*1)-(1-(2-3-(4-5)))+1');

echo 'RESULT=' . p(FORMULA);

function p($expr, $offset=0) {
  $operands = array();
  while ($offset < strlen($expr)) {
    if (count($operands) == 3) {
      $operands = proccess($operands);
    }

  if (isComplex($expr[$offset])) {
    ++$offset;// Отрезаю первую скобку выражения
    $complexVar = p($expr, &$offset);
    $operands[] = array((int)$complexVar, $expr[$offset]);
    if (strlen($expr) > $offset + 1 && ! isEnd($expr[$offset]))
      ++$offset;
    } elseif (isEnd($expr[$offset])) {
      // должно быть два элемента
      $left = array_shift($operands);
      $center = array_shift($operands);
      $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
      ++$offset;// Переходим к следующему сиволу после закрывающей скобки
      break;
    } elseif (preg_match('/(d)+/', $expr, $matches, 0, $offset)) {
      if (count($matches) > 1) {
        $operationPos = $offset + strlen($matches[1]);// Позиция операции=текущее смещение + длина
        if (($operationPos >= strlen($expr)) || isEnd($expr[$operationPos])) {// Конец выражения или строки
          if (count($operands) == 2) {
            $operands[] = array($matches[1], (strlen($expr) < $operationPos) ? $expr[$operationPos] : '');
            $operands = proccess($operands);
            $result = eval("return {$operands[0][0]} {$operands[0][1]} {$operands[1][0]};");
            if ($operationPos + 1 < strlen($expr))
              $offset = $operationPos + 1;
            break;
    } else {
      $result = eval("return {$operands[0][0]} {$operands[0][1]} {$matches[1][0]};");
      if ($operationPos + 1 < strlen($expr))
        $offset = $operationPos + 1;
      break;
    }
    } else {
  $operands[] = array((int)$matches[1], substr($expr, $operationPos, 1));
  // Сейчас позиция операции указывает на закрывающую скобку, двигаемся дальше
  if (strlen($expr) > $operationPos + 1)
    $offset = $operationPos + 1;
  }
    } else
      throw new Exception('?');
    } else {
      throw new Exception('?');
    }
  }

  return $result;
}

/*
* Из трех операндов делает два
*/
function proccess($operands) {
  if (in_array($operands[0][1], array('+', '-')) &&   (in_array($operands[1][1], array('*', '/')))) {
    // Центральный с правым
    $right = array_pop($operands);
    $center = array_pop($operands);
    echo "processing CR {$center[0]} {$center[1]} {$right[0]};n";
    $result = eval("return {$center[0]} {$center[1]} {$right[0]};");
    array_push($operands, array($result, $right[1]));
  } else {
    $left = array_shift($operands);
    $center = array_shift($operands);
    $result = eval("return {$left[0]} {$left[1]} {$center[0]};");
    echo "processing LC {$left[0]} {$left[1]} {$center[0]}=$result;n";
    array_unshift($operands, array((int)$result, $center[1]));
  }
  return $operands;
}

function isComplex($symbol) {
  return ($symbol == '(') ? TRUE : FALSE;
}

function isEnd($symbol) {
  return ($symbol == ')') ? TRUE : FALSE;
}