Андрей Маркелов Основы облачного хранилища данных Ceph Часть 1. Архитектура # ps aux | grep qemu-kvm ----------------------------------------------------- Александр Пичкасов Кастомизация гостевых ОС Управление гостевой ОС средствами хоста виртуализации Листинг 1 # Проверка аргумента if (-not ($args) -or ($args).count -gt 1) { Write-host "Usage: AutoDeploy.ps1 " Write-host " where 'virtualmachinefolder' - folder with virtulal machine files config.xml." Exit } # Проверка установки модуля pshyperv if (-not(Get-Module hyperv)) {import-module hyperv} if (-not(Get-Module hyperv)) { Write-Host "Install module 'HyperV'" Exit} #Проверка корректности аргумента – наличие каталога $vmPath = $args[0] if (Test-Path $vmPath){ $VMFolder = Get-Item -Path $vmPath\ } else { Write-Host "Virtual Machine Folder not found" Exit } if(-not ($VMFolder.PSisContainer)) { Write-Host "Virtual Machine's item is not folder." Exit } $savedir=$pwd #Импорт ВМ Write-Host "Import VM in folder " $VMFolder.FullName $Exists = Get-VM -name ([string] $VMFolder.Name) -ErrorAction SilentlyContinue If (!($Exists)){ Write-Host ("Importing virtual machine : ") -noNewLine Write-Host ([string] $VMFolder.Name) -foreground Green Write-Host Virtual Machine path: ([string] $VMFolder.FullName) Import-VM -path ([string] $VMFolder.FullName) -Wait Write-Host } Else { Write-Host ('Virtual machine "') -noNewLine Write-Host ([string] $VMFolder.Name) -noNewLine -foreground Yellow Write-Host ('" does already exist.') } #Создание виртуального сетевого коммутатора и подключение #к нему виртуального сетевого адаптера $tswitch = Get-VMSwitch -VirtualSwitchName "testswitch" if (-not $tswitch) { $tswitch = New-VMPrivateSwitch -VirtualSwitchName "TestSwitch" | Out-Null } Get-VM -name ([string] $VMFolder.Name) | Get-VMNIC | Set-VMNICSwitch -VirtualSwitch $tswitch.elementname #Получение файлов виртуальных дисков в каталоге $VHDs = get-childitem "$VMFolder\virtual hard disks\*.vhd" foreach ($VHD in $VHDs) { if ($vhd -and ($vhd.length -ne 0)) { Write-Host "Mounting for modification VHD " $VHD.FullName #Монтирование виртуального диска и поиск #системного раздела $volbefore = gwmi -Namespace root\cimv2 -Class win32_volume Mount-VHD -VHDPaths $VHD.FullName | Out-Null $volafter = gwmi -Namespace root\cimv2 -Class win32_volume # Поиск системного тома (критерий – максимальный # размер, вновь подключенный диск) $volsel = $null foreach ($vol in $volafter) { $cont = $false foreach ($volb in $volbefore) { if ($volb.deviceid -eq $vol.deviceid){ $cont = $true } } if (-not ($cont)) { if ($volsel) { if ($vol.capacity -gt $volsel.capacity) { $volsel = $vol } } else { $volsel = $vol } } } $sysdrive=$volsel.driveletter Листинг 2. if ($sysdrive) { Write-Host "Drive letter for SysDrive is " $sysdrive Write-Host "This volume on the one of partitions of VHD " $VHD.FullName if (Test-Path $sysdrive\windows\system32) { #Создание структуры папок для стартовых скриптов #и конфигурационных файлов new-item $sysdrive\windows\system32\grouppolicy -itemtype directory -ErrorAction SilentlyContinue | Out-Null new-item $sysdrive\windows\system32\grouppolicy\ machine -itemtype directory -ErrorAction SilentlyContinue | Out-Null new-item $sysdrive\windows\system32\grouppolicy\ user -itemtype directory -ErrorAction SilentlyContinue | Out-Null new-item $sysdrive\windows\system32\grouppolicy\ machine\scripts -itemtype directory -ErrorAction SilentlyContinue | Out-Null new-item $sysdrive\windows\system32\grouppolicy\ machine\scripts\startup –itemtype directory -ErrorAction SilentlyContinue | Out-Null new-item $sysdrive\windows\system32\grouppolicy\ machine\scripts\shutdown -itemtype directory -ErrorAction SilentlyContinue | Out-Null #Создание конфигурационных файлов групповых политик $StrGptIni = '[General]' + "`r`n" + 'gPCMachineExtensionNames=[ {42B5FAAE-6536-11D2-AE5A-0000F87571E3} {40B6664F-4972-11D1-A7CA-0000F87571E3}]' + "`r`n" + 'Version=5' out-file -filepath "$sysdrive\windows\system32\ grouppolicy\gpt.ini" -InputObject $StrGptIni -encoding ascii | Out-Null $StrScriptsIni= "`r`n" + '[Startup]' + "`r`n" + '0CmdLine=c:\windows\system32\ grouppolicy\machine\scripts\startup\ startup.cmd' + "`r`n" + '0Parameters=' + "`r`n" + '[Shutdown]' + "`r`n" + '0CmdLine=c:\windows\system32\ grouppolicy\machine\scripts\shutdown\ remove.cmd' + "`r`n" + '0Parameters=' out-file -filepath "$sysdrive\windows\system32\ grouppolicy\machine\scripts\scripts.ini" -inputobject $StrScriptsIni -encoding ascii | Out-Null #Создание стартового скрипта $StrStartupCmd = 'For /f "skip=3 tokens=4*" %%a In (' + "'NetSh Interface IPv4 Show Interfaces'" + ') Do (Call :UseNetworkAdapter %%a "%%b") ' + "`r`n" + 'c:\windows\system32\shutdown.exe -f -s -t 30' + "`r`n" + 'Exit /B' + "`r`n" + ':UseNetworkAdapter' + "`r`n" + 'If %1==connected (@if %2 neq "Loopback Pseudo-Interface 1" ( netsh int ipv4 set addr %2 static 10.10.0.33 255.255.0.0 10.10.0.1))' + "`r`n" + 'Exit /B' + "`r`n" out-file –filepath "$sysdrive\windows\system32\ grouppolicy\machine\scripts\startup\ startup.cmd" -InputObject $StrStartupCmd -encoding ascii | Out-Null #Создание скрипта выключения гостевой ОС $StrRemoveCmd = 'del /q c:\windows\system32\ grouppolicy\machine\scripts\startup\ startup.cmd' + "`r`n" + 'del /q c:\windows\system32\grouppolicy\machine\ scripts\scripts.ini' + "`r`n" + 'del /q c:\windows\system32\grouppolicy\gpt.ini' + "`r`n" + 'c:\windows\system32\reg.exe delete "HKLM\software\microsoft\windows\ currentversion\group policy\Status\ GPExtensions\{42B5FAAE-6536-11D2-AE5A- 0000F87571E3}" /f '+ "`r`n" + 'del /q c:\windows\system32\grouppolicy\machine\ scripts\shutdown\remove.cmd' out-file -filepath "$sysdrive\windows\system32\ grouppolicy\machine\scripts\shutdown\ remove.cmd" -InputObject $StrRemoveCmd -encoding ascii | Out-Null #Модификация ключей реестра для задействования CSE cd C:\Windows\System32 C:\Windows\System32\reg.exe load HKLM\onvhd $sysdrive\Windows\System32\config\ SOFTWARE | out-null reg add "HKLM\onvhd\microsoft\windows\ currentversion\group policy\Status\GPExtensions\{42B5FAAE-6536-11D2-AE5A-0000F87571E3}" /f | out-null reg add "HKLM\onvhd\microsoft\windows\ ↵ currentversion\group policy\Status\GPExtensions\{42B5FAAE-6536-11D2-AE5A- 0000F87571E3}" /v ForceRefreshFG /t REG_DWORD /d 0 /f | out-null reg add "HKLM\onvhd\microsoft\windows\ currentversion\group policy\Status\ GPExtensions\{42B5FAAE-6536-11D2-AE5A-0000F87571E3}" /v LastPolicyTime /t REG_DWORD /d 0 /f | out-null reg add "HKLM\onvhd\microsoft\windows\ currentversion\group policy\Status\ GPExtensions\{42B5FAAE-6536-11D2-AE5A-0000F87571E3}" /v PrevRsopLogging /t REG_DWORD /d 0 /f | out-null reg add "HKLM\onvhd\microsoft\windows\ currentversion\group policy\Status\ GPExtensions\{42B5FAAE-6536-11D2-AE5A-0000F87571E3}" /v PrevSlowLink /t REG_DWORD /d 0 /f | out-null reg add "HKLM\onvhd\microsoft\windows\ currentversion\group policy\Status\ GPExtensions\{42B5FAAE-6536-11D2-AE5A-0000F87571E3}" /v RsopStatus /t REG_DWORD /d 0 /f | out-null reg add "HKLM\onvhd\microsoft\windows\ currentversion\group policy\Status\ GPExtensions\{42B5FAAE-6536-11D2-AE5A-0000F87571E3}" /v Status /t REG_DWORD /d 0 /f | out-null reg unload HKLM\onvhd | out-null } } else { Write-Host "Drive letter not assigned for " $VHD.FullName } Dismount-VHD -VHDPaths $VHD.FullName -Force } } cd $saveDir Листинг 3. #Запуск ВМ $Exists = get-vm -name ([string] $VMFolder.Name) -ErrorAction SilentlyContinue If ($Exists){ Write-Host ("Starting virtual machine : ") -noNewLine Write-Host ([string] $VMFolder.Name) -foreground Green $exists | start-vm -wait #Ожидание завершения работы ВМ с проверкой 6-минутного #тайм-аута $checktime = (get-date).addminutes(6) while ((($exists | Get-VMState).enabledstate -eq "running") -and ((get-date).compareto($checktime) -lt 0)){ start-sleep 5 } #Если ВМ еще работает, запускается принудительное #выключение if (($exists | Get-VMState).enabledstate -eq "running") { Write-Host "Forced shutdown VM " $exist.elementname $exists | Invoke-VMShutdown -force -ShutdownTimeOut 2 } while (-not (($exists | Get-VMState).enabledstate -eq "stopped")){ start-sleep 1 } if (($exists | Get-VMState).enabledstate -eq "stopped") { # Создание снимка виртуальной машины Write-Host "Create snapshot for virtual machine " $exists.elementname $exists | New-VMSnapshot -Wait -Force -Note "StartImage" | Out-Null } Write-Host } Else { Write-Host ('Virtual machine "') -noNewLine Write-Host ([string] $DriveDstFolder.Name) -noNewLine -foreground magenta Write-Host ('" does not exist. Skip.') } Листинг 4. #Подготовка содержимого командного файла $StrCmd = 'For /f "skip=3 tokens=4*" %%a In (' + "'NetSh Interface IPv4 Show Interfaces'" + ') Do (Call :UseNetworkAdapter %%a "%%b") ' + "`r`n" + 'c:\windows\system32\shutdown.exe -f -s -t 30' + "`r`n" + 'Exit /B' + "`r`n" + ':UseNetworkAdapter' + "`r`n" + 'If %1==connected (@if %2 neq "Loopback Pseudo-Interface 1" ( netsh int ipv4 set addr %2 static 10.10.0.33 255.255.0.0 10.10.0.1))' + "`r`n" + 'Exit /B' + "`r`n" # Сохранение файла в файловой системе хоста виртуализации out-file –filepath "c:\changeip.cmd" -InputObject $StrCmd -encoding ascii | Out-Null #Копирование файла в гостевую операционную систему Copy-VMGuestFile -Source c:\changeip.cmd -Destination c:\temp\ -VM "VMname" -LocalToGuest -GuestUser Administrator -GuestPassword Pa$$w0rd #Выполнение подготовленного командного файла Get-VM "VMname" | Invoke-VMscript -ScriptText "c:\temp\changeip.cmd" -ScriptType Bat -GuestUser Administrator -GuestPassword Pa$$w0rd Листинг 5. Get-VM "VMname" | Invoke-VMscript -ScriptText 'New-NetIPAddress -InterfaceIndex ((Get-NetAdapter).ifindex) -IPAddress 10.10.0.33 -PrefixLength 16’ -GuestUser Administrator -GuestPassword Pa$$w0rd ---------------------------------------------------------------------- Александр Тетюшев Периферийный сервер #!/bin/bash for i in `ls /dev/disk/by-uuid`; do if [ -z `grep $i /etc/fstab| awk '{print $1 }'` ] ;then if [ ! -d /mnt/new ]; then mkdir /mnt/new; fi if [ ! -d /mnt/old ]; then mkdir /mnt/old; fi mount -o bind / /mnt/old if [ ! $? -eq 0 ]; then echo "ERROR mount /" && exit 1; fi mount /dev/disk/by-uuid/$i /mnt/new if [ ! $? -eq 0 ]; then echo "ERROR mount $i" && exit 1; fi rsync –atp --delete /mnt/old/ /mnt/new/ touch /mnt/new/.autorelabel sed -e '/ \/ /s/UUID=\(.*\)\//UUID='$i' \/ /' /mnt/old/etc/fstab >/mnt/new/etc/fstab umount /mnt/old umount /mnt/new fi done default=0 timeout=5 splashimage=(hd0,0)/grub/splash.xpm.gz hiddenmenu title CentOS 6.7(/dev/sda2) root (hd0,0) kernel /vmlinuz-2.6.32-573.7.1.el6.x86_64 ro root=/dev/sda2 LANG=ru_RU.UTF-8 rd_NO_LUKS rd_NO_MD KEYBOARDTYPE=pc KEYTABLE=ru rd_NO_LVM rd_NO_DM rhgb quiet initrd /initramfs-2.6.32-573.7.1.el6.x86_64.img title CentOS 6.7 (/dev/sda4) root (hd0,0) kernel /vmlinuz-2.6.32-573.7.1.el6.x86_64 ro root=/dev/sda4 LANG=ru_RU.UTF-8 rd_NO_LUKS rd_NO_MD KEYBOARDTYPE=pc KEYTABLE=ru rd_NO_LVM rd_NO_DM rhgb quiet initrd /initramfs-2.6.32-573.7.1.el6.x86_64.img # grub-install /dev/sda #curl https://get.docker.com/ |sh #chkconfig docker on && service docker start # docker search centos6.7 # docker pull abuecker/centos6.7 # docker run –i –t abuecker/centos6.7 /bin/sh #cd /usr/src #mkdir provider &&touch provider/Dockerfile #Version: 0.0.1 FROM abuecker/centos6.7 MAINTAINER #tetav@mail.ru RUN groupadd -g 1000 squid \ && useradd -u 1000 squid -g 1000 \ && yum –y update \ && yum -y install squid \ && chkconfig squid on \ && service squid start VOLUME ["/var/log/squid"] EXPOSE 8081 # cd provider && docker build –t=provider1:v1 . #docker images #docker run –i –t provider1:v1 /bin/sh # ps –ef |grep squid #!/bin/bash speedUp=$1 speedDown=$2 #Удаление очередей /sbin/tc qdisc del dev eth0 ingress /sbin/tc qdisc del dev eth0 root handle 1: # Ограничение скорости отдачи /sbin/tc qdisc add dev eth0 root handle 1: htb default 10 r2q 1 /sbin/tc class add dev eth0 parent 1: classid 1:10 htb rate ${speedUp}kbit quantum 8000 burst 8k # Ограничение скорости загрузки /sbin/tc qdisc add dev eth0 handle ffff: ingress /sbin/tc filter add dev eth0 parent ffff: protocol ip prio 50 u32 match ip src 0.0.0.0/0 police rate ${speedDown}kbit burst 12k drop flowid :1 /root/shapeSpeed.sh 50000 10000 acl all src 0.0.0.0/0.0.0.0 # сеть docker 172.17.0.0/16 acl localnet src 172.17.0.0/16 # 192.168.0.1 – адрес провайдера tcp_outgoing_address 192.168.0.1 localnet udp_outgoing_address 192.168.0.1 localnet http_access allow localnet http_access deny all # порт, на котором squid ждет клиентов http_port 8081 # docker ps | grep provider1:v1 # docker commit 2af60ad97380 provider1:v1 #mkdir /usr/src/provider2&&touch /usr/src/provider2/Dockerfile #Version: 0.0.1 FROM abuecker/centos6.7 MAINTAINER #tetav@mail.ru RUN groupadd -g 1000 squid \ && useradd -u 1000 squid -g 1000 \ && yum –y update \ && yum -y install squid \ && chkconfig squid on \ && service squid start VOLUME ["/var/log/squid"] EXPOSE 8082 #cd /usr/src/provider2&&docker build –t=provider2:v1 . acl all src 0.0.0.0/0.0.0.0 # 172.17.0.0/16 – внутреняя сеть docker acl localnet src 172.17.0.0/16 #192.168.100.1 адрес провайдера Wi-Fi tcp_outgoing_address 192.168.100.1 localnet udp_outgoing_address 192.168.100.1 localnet http_access allow localnet http_access deny all # порт, на котором squid ждет клиентов http_port 8082 # yum install squid # контейнеры как родительские кэши с перебором cache_peer provider2:v1 parent 8080 3130 no-query no-digest round-robin cache_peer provider1:v1 parent 8081 3130 no-query no-digest round-robin # стандартный порт, на котором базовый squid ждет # соединения http_port 192.168.1.200:3129 # iptables -t nat –A PREROUTING -p tcp --dport 80 –j REDIRECT --to-port 3129 #!/bin/bash for i in ` /usr/bin/docker ps | awk ‘{ if (!/CONTAINER/) print $1 }’` do host=`/usr/bin/docker ps|grep $i | awk ‘{print $2}’` # удаляем строки с таким именем sed –i ‘/$host/d’ /etc/hosts ip=’/usr/bin/docker inspect –f "{{ .NetworkSettings.IPAddress }}" $i` # устанавливаем имена хостов в /etc/hosts echo $ip $host >>/etc/hosts done /bin/docker run –d –i -t provider1:v1 /bin/docker run –d –i –t provider2:v1 /root/docker2hosts.sh ------------------------------------------------------------ Игорь Орещенков Удаленная поддержка пользователей net use \\workstation /user:domain\login password net use \\workstation /user:workstation\login password net use \\workstation /d plink.exe -N -L 5922:192.168.243.128:5900 192.168.243.128 ------------------------------------------------------------- Рашид Ачилов SSL в режиме повышенной безопасности # openssl ciphers -v # openssl ciphers -V 'EECDH+AESGCM:EECDH+AES:EDH+AESGCM: !SHA:!DSS:!SSLv2' EECDH+aRSA+AESGCM:EDH+aRSA+AESGCM:EECDH+aRSA+AES: EDH+aRSA+AES EECDH+AESGCM:EECDH+AES:EDH+AESGCM:!DSS:!SSLv2:EDH+3DES: EECDH+RC4 SSLCipherSuite EECDH+AESGCM:EECDH+AES:EDH+AESGCM:!DSS:!SSLv2 ssl_ciphers EECDH+AESGCM:EECDH+AES:EDH+AESGCM!DSS:!SSLv2; LOCAL_CONFIG O CipherList= EECDH+AESGCM:EECDH+AES:EDH+AESGCM!DSS:!SSLv2 ssl_cipher_list = EECDH+AESGCM:EECDH+AES:EDH+AESGCM!DSS: !SSLv2 SSLProtocol all -SSLv2 -SSLv3 ssl_protocols TLSv1.2 TLSv1.1 TLSv1; LOCAL_CONFIG O ServerSSLOptions=+SSL_OP_NO_SSLv2 +SSL_OP_NO_SSLv3 +SSL_OP_CIPHER_SERVER_PREFERENCE O ClientSSLOptions=+SSL_OP_NO_SSLv2 +SSL_OP_NO_SSLv3 ssl_protocols = !SSLv2 !SSLv3 SSLHonorCipherOrder on ssl_prefer_server_ciphers on; ssl_prefer_server_ciphers = yes # openssl dhparam -out /etc/pki/tls/dhparams.pem 2048 SSLOpenSSLConfCmd DHParameters "/etc/pki/tls/dhparams.pem" ssl_dhparam /etc/pki/tls/dhparams.pem LOCAL_CONFIG O DHParameters=/etc/pki/tls/dpparams.pem define(`confDH_PARAMETERS',`/etc/pki/tls/dhparams.pem') ssl_dh_parameters_length = 2048 Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" add_header Strict-Transport-Security "max-age=31536000; includeSubDomains"; # openssl x509 -noout -in certfile.pem -pubkey | openssl asn1parse -noout -inform pem -out public.key # openssl dgst -sha256 -binary public.key | openssl enc -base64 Header always set Public-Key-Pins "pin-sha256=\"<рассчитанный_SPKI>\";max-age=31536000; includeSubDomains" add_header Public-Key-Pins 'pin-sha256="<рассчитанный_SPKI>"; max-age=31536000; includeSubDomains'; ----------------------------------------------------------------- Сергей Маслов Опыт секционирования таблиц в Oracle Часть 4. Управление секциями и подсекциями Alter table ИМЯ ТАБЛИЦЫ ОПЕРАЦИЯ ИМЯ СЕКЦИИ или ПОДСЕКЦИИ Create table aif.histlog (isn number , updated date) partition by range (updated) (partition P_01 values less than (to_date('01.01.2015','DD.MM.YYYY')) , partition P_02 values less than (to_date('01.02.2015','DD.MM.YYYY')), partition P_03 values less than (to_date('01.03.2015','DD.MM.YYYY')), partition P_05 values less than (to_date('01.05.2015','DD.MM.YYYY')), partition P_MAX values less than (maxvalue)) enable row movement; Select * from all_tab_partitions where table_owner='AIF' and table_name='HISTLOG'; Select 'P_01',count(*) from aif.histlog partition(P_01) ... union all Select 'P_MAX',count(*) from aif.histlog partition(P_MAX); --новая секция Alter table aif.histlog add partition P_06 --граница новой секции values less than (to_date('01.06.2015','DD.MM.YYYY')) update global indexes; Alter table aif.histlog drop partition P_02 update global indexes; Alter table aif.histlog move partition P_01 tablespace aifdata nologging compress update global indexes; Alter table aif.histlog truncate partition P_03 update global indexes; -- имя расщепляемой секции Alter table aif.histlog split partition P_05 -- граница новой секции at (to_date('01.04.2015','DD.MM.YYYY')) -- имя новой секции into (partition P_04, -- имя расщепляемой секции partition P_05) update global indexes; Alter table aif.histlog split partition P_MAX at to_date('01.07.2015','DD.MM.YYYY')) into (partition P_07, partition P_MAX) update global indexes; Alter table aif.histlog split partition P_MAX at (to_date('01.08.2015','DD.MM.YYYY')) into (partition P_08, partition P_MAX) update global indexes; Alter table aif.histlog split partition P_MAX at (to_date('01.09.2015','DD.MM.YYYY')) into (partition P_09, partition P_MAX) update global indexes; Alter table aif.histlog merge partitions P_02, P_03 into partition P_02_03 update global indexes; Select table_owner, table_name, partition_name, high_value, tablespace_name, compression from all_tab_partitions where table_owner='AIF' and table_name='HISTLOG'; Create table aif.histlog_h (isn number , updated date) partition by hash(isn) partitions 8 enable row movement; Alter table aif.histlog_h coalesce partition update global indexes; Alter table aif.histlog rename partition P_03 to P_03_NEW; Alter table aif.histlog exchange partition P_05 --имя таблицы, в которую переносим with table aif.histlog_arx including indexes without validation update global indexes; Create table aif.histers(updated date, raions number) partition by Range(updated) interval(interval '1' MONTH) subpartition by List(raions) subpartition template (subpartition sub1 values(1), subpartition sub2 values(2)) (partition P_01 values less than (to_date('01.01.2015', 'DD.MM.YYYY')) ) enable row movement; Alter table aif.histers modify partition P_01 add subpartition sub3 values(3) ; Create table aif.histres_h(updated date, raions number) partition by Range(updated) interval(interval '1' MONTH) subpartition by hash(raions) subpartitions 8 (partition P_01 values less than (to_date('01.01.2015', 'DD.MM.YYYY')) ) enable row movement; Alter table aif.histers_h modify partition P_01 coalesce subpartition update global indexes; Create table aif.histres_list(updated date, raions number) partition by Range(updated) interval(interval '1' MONTH) subpartition by List(raions) (partition p_1 values less than (to_date('01.01.2015', 'DD.MM.YYYY')) (subpartition p_1_sub2 values(1,2)) ) enable row movement; Alter table aif.histres_list split subpartition P_1_SUB2 values(1) into (subpartition P_1_SUB1, subpartition P_1_SUB2) ORA-14619: resulting List subpartition(s) must contain at least 1 value Select table_owner,table_name,partition_name, subpartition_name, high_value, subpartition_position, tablespace_name, segment_created from all_tab_subpartitions where table_owner='ИМЯ СХЕМЫ' and table_name='ИМЯ ТАБЛИЦЫ'; Select * from all_tab_partitions P, all_tab_subpartitions S where p.table_owner=s.table_owner and p.table_name=s.table_name and p.partition_name=s.partition_name and p.table_owner ='ИМЯ СХЕМЫ' and p.table_name='ИМЯ ТАБЛИЦЫ' order by p.partition_position, s.subpartition_position; Alter table docimage modify partition docimage_1 lob(oleobject) (shrink space); Create table aif.pages(id number,page_data blob, created date,partid number) partition by range (partid) (partition pages_1 values less than (2), ... partition pages_12 values less than (13) ) enable row movement; Partid number generated always as(to_number( to_char (CREATED,'MM')))virtual Alter table aif.pages truncate partition(pages_1) update global indexes; Select tablespace_name, sum(bytes) free_bytes from dba_free_space group by tablespace_name order by 1; Partition by list (partid) (partition pages_1 values (1) , ... partition pages_12 values (12) ) Select 'pages_1' part, count(*) num_rows from AIF.PAGES partition(PAGES_1) union all Select 'pages _2', count(*) from AIF.PAGES partition(PAGES_2) ... union all Select 'pages _12', count(*) from AIF.PAGES partition(PAGES_12) ------------------------------------------- Александр Майоров Новый Nginx с HTTP/2 и JavaScript listen localhost:443 ssl http2; $ ./configure --with-http_ssl_module --with-http_v2_module --with-openssl=/path/to/openssl-1.0.2 server { listen 443 ssl http2 default_server; ... } nghttp -v https://tutu.ru server { listen 80; server_name domain.ru www.domain.ru; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name domain.tld www.domain.tld; ssl on; ssl_certificate /etc/nginx/ssl/domain.pem; ssl_certificate_key /etc/nginx/ssl/domain.key; ssl_prefer_server_ciphers On; ssl_protocols TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; location / { root /www/site/public; } } $ wget http://nginx.org/download/nginx-1.9.5.tar.gz $ tar -xzvf nginx-1.9.5.tar.gz $ hg clone http://hg.nginx.org/njs $ cd nginx-1.9.5 ./configure \ --sbin-path=/usr/sbin/nginx \ --conf-path=/etc/nginx/nginx.conf \ --pid-path=/var/run/nginx.pid \ --lock-path=/var/run/nginx.lock \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --user=www \ --group=www \ --with-ipv6 \ --with-pcre-jit \ --with-http_gzip_static_module \ --with-http_ssl_module \ --with-http_v2_module \ --add-module=../njs/nginx \ $ make -j2 $ make install js_set $msg " var m = 'Hello '; m += 'world!'; m; "; server { … location /hello { add_header Content-Type text/plain; return 200 $msg; } … } location /hello { js_run " var res; res = $r.response; res.contentType = 'text/plain'; res.status = 200; res.sendHeader(); res.send( 'Hello, world!' ); res.finish(); "; } js_set $summary " var a, s, h; s = 'Request summary\n\n'; s += 'Method: ' + $r.method + '\n'; s += 'HTTP version: ' + $r.httpVersion + '\n'; s += 'Host: ' + $r.headers.host + '\n'; s += 'Remote Address: ' + $r.remoteAddress + '\n'; s += 'URI: ' + $r.uri + '\n'; s += 'Headers:\n'; for (h in $r.headers) { s += ' header \"' + h + '\" is \"' + $r.headers[h] + '\"\n'; } s += 'Args:\n'; for (a in $r.args) { s += ' arg \"' + a + '\" is \"' + $r.args[a] + '\"\n'; } s; "; location /js/getfib { js_run " function fib(n) { var prev = 1, curr = 1, newc, i; if (n < 2) return n; for (i = 3; i <= n; i++) { newc = prev + curr; prev = curr; curr = newc; } return curr; } var n = +$r.args['n'], txt = 'Fibonacci( ' + n + ' ) = ' + fib(n), res = $r.response; res.contentType = 'text/plain'; res.status = 200; res.sendHeader(); res.send(txt); res.send('\n'); res.finish(); "; } newc = prev + curr; prev = curr; curr = newc; [ prev, curr ] = [ curr, prev + $curr ]; prev = [ curr, prev += curr ][0]; upstream my_upstream0 { server server1.example.com; server server2.example.com; } upstream my_upstream1 { server server3.example.com; server server4.example.com; } js_set $my_upstream " var s, upstream, upstream_num; upstream = $r.args.upstream; // convert upstream number to integer upstream_num = +upstream | 0; if (upstream_num < 0 || upstream_num > 1) { upstream_num = 0; } s = 'my_upstream' + upstream_num; s; "; server { listen 80; location / { proxy_set_header Host $host; proxy_pass http://$my_upstream; } } ----------------------------------------- Андрей Пахомов Виджеты в Android: теория и практика android:minHeight="50dp" android:minWidth="200dp" android:initialLayout="@layout/widget_layout" android:previewImage="@drawable/widget_icon" android:updatePeriodMillis="300000"> ... @Override public void onUpdate(...) { super.onUpdate(context, appWidgetManager, appWidgetIds); for (int i : appWidgetIds) { updateWidget(…);} } void updateWidget(...) { RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout); setList(rv, context, appWidgetId); setRefreshField(rv, context, appWidgetId);...} TelephonyManager tm; tm=(TelephonyManager)context.getSystemService( Context.TELEPHONY_SERVICE); ArrayList items = new ArrayList(); items.add("Device ID: " + tm.getDeviceId()); @Override public RemoteViews getViewAt(int position) { RemoteViews row=new RemoteViews(ctxt.getPackageName(), R.layout.listview_element); row.setTextViewText(R.id.data, items.get(position)); return(row);} @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new CustomListViewFactory(getApplicationContext(), intent);} Intent adapterIntent = new Intent(context, WidgetService.class); adapterIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); Uri data = Uri.parse(adapter.toUri(Intent.URI_INTENT_SCHEME)); adapter.setData(data); rv.setRemoteAdapter(R.id.listview, adapterIntent);} ---------------------------------------------------------------- Александр Календарев Кролик в песочнице Queue.bind($key, $exchange_name); Exchange.bind($queue_name, $routing_key); sudo apt-get install rabbitmq-server docker pull rabbitmq sudo pecl install amqp // (1) sudo pip install pika==0.10.0 // (2) !/usr/bin/env python import pika connection = pika.BlockingConnection( pika.ConnectionParameters('localhost')) channel = connection.channel() !/usr/bin/php 'localhost', 'port' => '5672', 'login' => 'guest', 'password' => 'guest' ]); $rabbit->connect(); $сhannel = new AMQPChannel($rabbit); !/usr/bin/env python import pika connection = pika.BlockingConnection() channel = connection.channel() channel.exchange_declare(exchange="test_exchange", exchange_type="direct", passive=False, durable=True, auto_delete=False) $sudo rabbitmqctl list_exchanges #!/usr/bin/php connect(); $testChannel = new AMQPChannel($rabbit); $queue = new AMQPQueue($testChannel); $queue->setName('test_queue'); $queue->declare(); $rabbit->disconnect(); $sudo rabbitmqctl list_queues >>> import pika >>> connection = pika.BlockingConnection() >>> channel = connection.channel() >>> channel.basic_publish('test_exchange', 'my_key', 'test message 1', pika.BasicProperties( content_type='text/plain', delivery_mode=1)) #!/usr/bin/php connect(); $testChannel = new AMQPChannel($rabbit); $queue = new AMQPQueue($testChannel); $queue->setName('test_queue'); $queue->bind('test_exchange', 'my_key'); $rabbit->disconnect(); $ sudo rabbitmqctl list_bindings $rabbit = new AMQPConnection(); $res = $rabbit->connect(); $testChannel = new AMQPChannel($rabbit); $queue = new AMQPQueue($testChannel); $queue->setName('test_queue'); $msg = $queue->get(); $rabbit->disconnect(); var_dump($msg); // вывод: object(AMQPEnvelope)#4 (18) { ["body"] => string(11) "test message 1" ["content_type"]=> string(10) "text/plain" ["routing_key"]=> string(6) "my_key" ["delivery_tag"]=> int(1) ["delivery_mode"]=> int(1) ["exchange_name"]=> string(13) "test_exchange" ["is_redelivery"]=> int(0) ["content_encoding"]=> string(0) "" ["type"]=> string(0) "" ["timestamp"]=> int(0) ["priority"]=> int(0) ["expiration"]=> string(0) "" ["user_id"]=> string(0) "" ["app_id"]=> string(0) "" ["message_id"]=> string(0) "" ["reply_to"]=> string(0) "" ["correlation_id"]=> string(0) "" ["headers"]=> [] } function processMessage($envelope, $queue) { static $i=0; echo 'Message ',$i,': ',$envelope->getBody(), PHP_EOL; $i++; if($i > 10){ return false; } } $rabbit = new AMQPConnection(); $res = $rabbit->connect(); $testChannel = new AMQPChannel($rabbit); $queue = new AMQPQueue($testChannel); $queue->setName('test_queue'); $queue->consume("processMessage"); ----------------------------------------