2014年8月19日 星期二

[Linux] 初次使用 Docker 筆記 @ Ubuntu 14.04

最近找尋系統監控的方式時,無意間看到 Docker 的消息,雖然以前用過 LXC 一陣子,久了沒用又都忘光光,這次 Docker 還滿紅的,就順手學一下吧!若安裝前,想體驗一下,可以試看看官網推的教學模式:https://www.docker.com/tryit/

在使用前,想說找一下 Docker 的商業模式,找了很久都沒看到 XD 直到使用 Docker hub 時才發現,商業模式就像 github/bitbucket 一樣,想要建立 private repo 的則需要付費,此例就是可以打包自己的開發環境送到 Docker hub 上使用,免費方案有提供 1 個 private 單位哦。


回到筆記,根據官網介紹 https://docs.docker.com/installation/ubuntulinux/,依序幾個動作就完成安裝了:

$ sudo apt-get update
$ sudo apt-get install docker.io
$ sudo ln -sf /usr/bin/docker.io /usr/local/bin/docker
$ sudo sed -i '$acomplete -F _docker docker' /etc/bash_completion.d/docker.io


開始使用:

$ sudo docker run ubuntu:12.04 echo "hello world"
Unable to find image 'ubuntu:12.04' locally
Pulling repository ubuntu
822a01ae9a15: Download complete
511136ea3c5a: Download complete
93c381d2c255: Download complete
a5208e800234: Download complete
9fccf650672f: Download complete
1186c90e2e28: Download complete
f6a1afb93adb: Download complete
hello world


此命令是說要跑一個 ubuntu 12.04 環境,在其環境執行 echo "hello world" 的意思,整個過程就是包含初始化(下載image)後,最後在執行 echo "hello world",有興趣可以再執行一次,這次就不會再去下載 image 了。

然而,上述的動作只是一次性的,舉例來說,初始環境執行 apt-get install curl 是會出錯的:

$ sudo docker run ubuntu:12.04 apt-get install curl
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package curl


但只要 apt-get update 後就會正常,但不能分開執行:

$ sudo docker run ubuntu:12.04 apt-get update
Get:1 http://archive.ubuntu.com precise Release.gpg [198 B]
Get:2 http://archive.ubuntu.com precise-updates Release.gpg [198 B]
Get:3 http://archive.ubuntu.com precise-security Release.gpg [198 B]
...
Reading package lists...
$ sudo docker run ubuntu:12.04 apt-get install curl
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package curl


因此,正式的使用其實是開個 terminal 進去連續動作:

$ sudo docker run -t -i ubuntu:12.04
root@431bb00c701d:/#


其中 431bb00c701d 則是此 container ID,

root@431bb00c701d:/# apt-get install wget
Reading package lists... Done
Building dependency tree    
Reading state information... Done
E: Unable to locate package wget
root@431bb00c701d:/# apt-get update
...
root@431bb00c701d:/# apt-get install wget
Reading package lists... Done
Building dependency tree      
Reading state information... Done
The following extra packages will be installed:
  libidn11
The following NEW packages will be installed:
  libidn11 wget
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 391 kB of archives.
After this operation, 966 kB of additional disk space will be used.
Do you want to continue [Y/n]?


接著按 exit 離開後,其實就跟上述單行指令操作一樣,什麼都沒留下,因此在離開之前,想要保存環境則是要進行 commit。

此時,必須額外再開一個 terminal 用 docker ps 查看目前已執行的 image 環境:

$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5db62a9bf492        ubuntu:14.04        /bin/bash           11 seconds ago      Up 10 seconds                           goofy_curie      
431bb00c701d        ubuntu:12.04        /bin/bash           35 seconds ago      Up 34 seconds                           agitated_thompson


此例代表有2個 container 在運行,此例目標是 ubuntu:12.04 的 431bb00c701d ,想要儲存環境變化,就來個 commit 吧

$ sudo docker commit -m 'ubuntu 12.04 with wget' 431bb00c701d
$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
<none>              <none>              aac0f5ce2936        9 minutes ago       137.7 MB
ubuntu              14.04               c4ff7513909d        7 days ago          213 MB
ubuntu              12.04               431bb00c701d        7 days ago          108 MB


想要有更佳的描述,就在 docker commit  時,多加一點資訊 REPOSITORY[:TAG] 吧:

$ sudo docker commit -m 'ubuntu 12.04 with wget' e7e35769932d MyUbuntu:12.04
$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED              VIRTUAL SIZE
MyUbuntu            12.04               d3466dce0e51        About a minute ago   108 MB
<none>              <none>              aac0f5ce2936        10 minutes ago       137.7 MB
ubuntu              14.04               c4ff7513909d        7 days ago           213 MB
ubuntu              12.04               431bb00c701d        7 days ago           108 MB


下次要用時:

$ sudo docker run -i -t MyUbuntu:12.04
root@600d3fee924d:/# wget
wget: missing URL
Usage: wget [OPTION]... [URL]...

Try `wget --help' for more options.


@ 2014-10-24 加映場:[Linux] Docker 使用筆記 - 常用指令 @ Ubuntu 14.04

2014年8月18日 星期一

iOS 開發教學 - 邀請使用者評論、評分 iOS app (Review/Rate your iOS app)

原理就是第一次使用時,埋一個時間進去,等下次使用者使用 iOS app 時,判斷時間是否夠長,達到時間間距時,使用 UIAleterView 詢問使用者是否願意 Rate your app。

假設 iOS app 預設啟用時,停留在某個 ViewController:

@interface ViewController () <UIAlertViewDelegate>
// ...
@end


@implementation ViewController

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case YOUR_APP_ID:
        {
            //NSLog(@"buttonIndex: %d", buttonIndex);
            NSDate * now = [[NSDate alloc] init];
            switch (buttonIndex) {
                case 1: // YES
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%d", alertView.tag]]];
                    [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"rateDone"];
                    break;
                case 2: // Remind me later
                    [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"rateDate"];
                    break;
                default:
                    [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"rateDone"];
                    break;
            }
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
            break;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    @try {
        //[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"rateDone"];
        //[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"rateDate"];
        //[[NSUserDefaults standardUserDefaults] synchronize];
     
        if (![[NSUserDefaults standardUserDefaults] objectForKey:@"rateDone"]) {
            NSDate * now = [[NSDate alloc] init];
            if (![[NSUserDefaults standardUserDefaults] objectForKey:@"rateDate"]) {
                [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"rateDate"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            } else {
                NSDate *prevDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"rateDate"];
                if ([now timeIntervalSinceDate:prevDate] > 60 * 60 * 10) {
                    UIAlertView *alterView = [[UIAlertView alloc] initWithTitle:@"Rate this app" message:@"If you enjoy using this app, would you mind taking a moment to rate it?" delegate:self cancelButtonTitle:@"NO, Thanks" otherButtonTitles:@"YES", @"Remind me later", nil];
                    alterView.tag = YOUR_APP_ID;
                    [alterView show];
                }
            }
        }
    }
    @catch (NSException *exception) {
    }
    @finally {
    }
}

@end

2014年8月17日 星期日

iOS 開發教學 - UITableViewController 與 UIRefreshControl 用法 (Pull to Refresh)

呃,太久沒摸 UITableViewController 了,有一陣子都用 Storyboard 去刻,最近想說返樸歸真,改用純 coding 的方式,馬上想到如何處理 Pull to refresh 這個議題。

因為用 CocoaPods 一陣子,馬上就用關鍵字搜尋一下,發現有幾款不錯,但總是覺得差那麼一點,例如超過一年沒更新,當年熱門的甚至四年沒更新了 Orz 想了一會兒,才驚醒是不是變成內建了 XD 才想到之前去年底複習 CS193P 時,就看到教學過,那時是使用 Storyboard 的用法,隨意勾一勾就有的東西。

總之,回到主題,純寫 code 的方式,以 UITableViewController 而已,就是配置 self.refreshControl 就對了!

- (void)refreshData
{
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Loading..."];
    dispatch_async(dispatch_queue_create("loading...", NULL), ^{
        [NSThread sleepForTimeInterval:5];
      
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.refreshControl endRefreshing];
            self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to refresh"];
        });
    });
}

- (void)viewWillAppear:(BOOL)animated
{
    if (!self.refreshControl)
        self.refreshControl = [[UIRefreshControl alloc] init];
    if (!self.refreshControl.isRefreshing) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView setContentOffset:CGPointMake(0, -self.refreshControl.frame.size.height - self.navigationController.navigationBar.frame.size.height) animated:YES];
            [self.refreshControl beginRefreshing];
            [self refreshData];
        });
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (!self.refreshControl)
        self.refreshControl = [[UIRefreshControl alloc] init];
    if (self.refreshControl) {
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to refresh"];
        [self.refreshControl addTarget:self action:@selector(refreshData) forControlEvents:UIControlEventValueChanged];
    }
}


雖然很簡單,還是筆記一下 Orz

2014年8月14日 星期四

[PHP] 使用 Mantis SOAP API - 新增 issue custom_fields

架好 Mantis 後,預設是有開啟 SOAP API 的,可以瀏覽 http://server_ip/mantis/api/soap/mantisconnect.php?wsdl 試試,應該會看到 SOAP API 的使用列表跟使用方式。

對於 custom_fields 的用法,可用在新增一些額外的資料屬性來記錄,必須先新增 custom_fields:

Manage -> Manage Custom Fields -> 填寫想的欄位名字 -> New Custom Field -> 在 Write Access 請填寫 Reporter 以及 Display 的區域也勾一勾 -> update custom field,別忘了下方也要選擇使用的 project 並點選 Link Custom Field

接著,在使用 Mantis SOAP API 時,必須先用 mc_project_get_custom_fields 把 custom_fields 的資料撈出來,因為在使用 mc_issue_add 時,對於 custom_fields 必須填寫 id 跟 name:

// 使用 Hash 來記錄
$custom_fields = array();
foreach( $c->mc_project_get_custom_fields($user, $pass, $project_id) as $raw )
        if (isset($raw->field->name) )
                $custom_fields[$raw->field->name] = $raw->field;


最後再新增 issue data 時,記得 custom_fields 是一個 Array of Object,所以新增的額外欄位資料,請用:

$field_item = new stdClass();
$field_item->field = $custom_fields["Custom_field_name"];
$field_item->value = $custom_fields_value["Custom_field_name"];


例如:

$issue_data = array(
        'project' => array(
                        'id' => $project_id
                ),
        'category' => $issus_category,
        'summary' => $issue_summary,
        'description' => $issue_description,
'custom_fields' => array()
);

$field_item = new stdClass();
$field_item->field = $custom_fields["Custom_field_name"];
$field_item->value = $custom_fields_value["Custom_field_name"];

array_push( $issue_data['custom_fields'] , $field_item );

$issus_id = $c->mc_issue_add($user, $pass, $issue_data);

2014年8月12日 星期二

[PHP] 使用 Mantis SOAP API - Automatically Create an Issue



架好 Mantis 後,預設是有開啟 SOAP API 的,可以瀏覽 /mantis/api/soap/mantisconnect.php?wsdl 試試,應該會看到 SOAP API 的使用列表跟使用方式。

使用上需要指定 user, password 跟 project id,目前沒找到一口氣列出所有 project 的方法?倒是可以用 project name 找 project id,而發一則 issue 必須要有的資訊:project id, category, summary, description,連續動作:

<?php
$c = new SoapClient('http://YourMantisServerIP/mantis/api/soap/mantisconnect.php?wsdl');

$user = 'report_account';
$pass = 'report_password';
$project_name = 'ProjectName';

$issue_summary = 'Report title';
$issue_description = 'Report body';
$issus_category = 'iOS';

$project_id = $c->mc_project_get_id_from_name($user, $pass, $project_name);
if ($project_id == 0) {
        echo "[ERROR] Project ID Not Found: [$project_name]\n";
        exit;
}

$categories = $c->mc_project_get_categories($user, $pass, $project_id);
print_r($categories);

//$custom_fields = $c->mc_project_get_custom_fields($user, $pass, $project_id);
//print_r($custom_fields);

$issue_data = array(
        'project' => array(
                        'id' => $project_id
                ),
        'category' => $issus_category,
        'summary' => $issue_summary,
        'description' => $issue_description
);

$issus_id = $c->mc_issue_add($user, $pass, $issue_data);

echo "Issue ID: $issus_id\n";


成功的話,就會看到最後印出的 Issue ID。

對於 SOAP 的簡介可以參考:如何透過PHP、SOAP 及 WSDL撰寫Web Service